http://acm.hdu.edu.cn/showproblem.php?pid=1518
算法参考:http://blog.csdn.net/w00w12l/article/details/7865348
Problem Description
Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square?
Input
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.
Output
For each case, output a line containing "yes" if is is possible to form a square; otherwise output "no".
Sample Input
3
4 1 1 1 1
5 10 20 30 40 50
8 1 7 2 6 4 4 3 5
Sample Output
yes
no
yes
#include<iostream> #include<algorithm> #include<cstring> #include<cstdio> using namespace std; int a[30]; bool vis[30]; int n,m,sum,len; bool dfs(int cur,int time ,int k) { if(time==3) return true; for(int i=k; i>=1; i--) { if(!vis[i]){ vis[i]=true; if(cur+a[i]==len){ if(dfs(0,time+1,m)) return true; } else if(cur+a[i]<len){ if(dfs(cur+a[i],time,i-1)) return true; //关键是i-1..不然会一直超时的。。 } vis[i]=false; } } return false; } int main() { scanf("%d",&n); while(n--) { scanf("%d",&m); sum=0; for(int i=1; i<=m; i++) { scanf("%d",&a[i]); sum+=a[i]; } memset(vis,0,sizeof(vis)); sort(a,a+m); if(sum%4==0&&a[m]<=sum/4&&m>=4) { len=sum/4; if(dfs(0,0,m)) printf("yes "); else printf("no "); } else printf("no "); } return 0; }