POJ 2362 / SCAU 2542 Square
2542 Square
时间限制:3000MS 内存限制:65536K
题型: 外判编程题 语言: 无限制
Description
Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square?
输入格式
The first line of input contains N, the number of test cases. Each test case begins with an integer 4 <= M <= 20, the number of sticks. M integers follow; each gives the length of a stick - an integer between 1 and 10,000.
输出格式
For each case, output a line containing "yes" if is is possible to form a square; otherwise output "no".
输入样例
3 4 1 1 1 1 5 10 20 30 40 50 8 1 7 2 6 4 4 3 5
输出样例
yes no yes
来源
Waterloo local 2002.09.21
作者
admin
1 #include<iostream> 2 #include<cstdio> 3 #include<string> 4 #include<cstring> 5 #include<algorithm> 6 #define MAXN 22 7 8 using namespace std; 9 10 int sticks[MAXN]; 11 bool visit[MAXN]; 12 int n, length, sumlen; 13 14 bool cmp(const int& a, const int& b) 15 { 16 return a>b; 17 } 18 19 bool Traverse(int num, int len, int cur) 20 { 21 if(num == 4) return true; 22 for(int i=cur; i<n; ++i) 23 { 24 if(!visit[i] && !(i && !visit[i-1] && sticks[i] == sticks[i-1])) 25 { 26 if(len+sticks[i] == length) 27 { 28 visit[i] = true; 29 if(Traverse(num+1, 0, 0)) return true; 30 visit[i] = false; 31 return false; 32 } 33 else if(len+sticks[i] < length) 34 { 35 visit[i] = true; 36 if(Traverse(num, len+sticks[i], i+1)) return true; 37 visit[i] = false; 38 if(len == 0) return false; 39 } 40 } 41 } 42 return false; 43 } 44 45 46 int main() 47 { 48 #ifndef ONLINE_JUDGE 49 // freopen("F:\\test\\input.txt", "r", stdin); 50 #endif // ONLINE_JUDGE 51 int t; 52 cin>>t; 53 while(t--) 54 { 55 sumlen = 0; 56 cin>>n; 57 for(int i=0; i<n; ++i) 58 { 59 cin>>sticks[i]; 60 sumlen += sticks[i]; 61 } 62 sort(sticks, sticks+n, cmp); 63 length = sumlen/4; 64 if(sumlen%4 || length < sticks[0]) 65 { 66 cout<<"no"<<endl; 67 continue; 68 } 69 memset(visit, false, sizeof(visit)); 70 if(Traverse(0, 0, 0)) cout<<"yes"<<endl; 71 else cout<<"no"<<endl; 72 } 73 return 0; 74 }
更多内容请关注个人微信公众号 物役记 (微信号:materialchains)
作者:雪影蓝枫
本文版权归作者和博客园共有,欢迎转载,未经作者同意须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。


浙公网安备 33010602011771号