@Chilling
        
        2017-01-16T08:20:00.000000Z
        字数 1188
        阅读 1175
    搜索
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
题意:每组数据给出n根木棒,长短不一,问是否能恰好用这n根木棒拼出一个正方形,n根木棒要用完。
#include<stdio.h>#include<algorithm>#include<string.h>using namespace std;int a[111],ave,l,n,ans;int vis[111];void dfs(int l,int count,int pos)//当前边长度,边数,当前搜索的位置{if(l>ave||ans==1) return; //如果当前长度大于ave则不可行if(count==3){ans=1;return;}if(l==ave) //该边长度满足{count++;l=0; //重置l与pos,开始下一边搜索pos=n-1;}for(int i=pos;i>=0;i--){if(vis[i]==0) //如果该木棒未被使用过{vis[i]=1;dfs(l+a[i],count,i-1);vis[i]=0; //回溯}}}int main(){int t,i,sum;scanf("%d",&t);while(t--){memset(a,0,sizeof(a));memset(vis,0,sizeof(vis));sum=0,l=1,ans=0;scanf("%d",&n);for(i=0;i<n;i++){scanf("%d",&a[i]);sum+=a[i];}sort(a,a+n);ave=sum/4;if(n<=3||sum%4!=0||a[n-1]>ave) //预处理printf("no");else{dfs(0,0,n-1);if(ans==1)printf("yes");elseprintf("no");}printf("\n");}return 0;}
