題目:給定6對整數,分別代表一個矩形的邊長,判斷是否能構成一個長方體。
思路:看似簡單,但要找對方法,否則還是很麻煩的。輸入的12個數,沒有什麼規律可言,爲了判斷方便,可以先進行標準化處理。
關鍵是數的關係,所以可以創建一個square結構體,包含兩個成員變量 ,分別代表矩形的較短邊和較長邊,這樣,就變成了6個矩形,然後對矩形進行排序,如何定義大小關係呢?先比較短邊,再比較長邊。
代碼
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct square{
int a,b;
square(int xa=0,int xb=0){
if(xa<xb){a=xa;b=xb;}
else{a=xb;b=xa;}
}
bool operator==(const square &sb) const{
return (a==sb.a&&b==sb.b);
}
bool operator < (const square &sb)const {
return a==sb.a?b<sb.b:a<sb.a;
}
} s[6];
int reads(){
int a,b;
for(int i=0;i<6;++i){
if(scanf("%d%d",&a,&b)!=2) return 0;
s[i]=square(a,b);
}
return 1;
}
bool check(){
sort(s,s+6);
for(int i=0;i<6;i+=2) if(!(s[i]==s[i+1])) return 0;
return(s[0].a==s[2].a&&s[0].b==s[4].a&&s[2].b==s[4].b);
}
int main(){
while(reads()){
printf("%s\n",check()?"POSSIBLE":"IMPOSSIBLE");
}
return 0;
}
疑惑:
- 重載運算符的函數必須聲明爲const,雖然我到現在也沒搞明白是爲什麼
- 構造函數不是沒有返回值嗎,那麼
s[i]=square(a,b);
爲什麼是對的呢?