HDU - 1518 :Square
阿新 • • 發佈:2017-07-28
form and esp line otherwise end || put void
Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square?
InputThe 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.
OutputFor 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
組成正方形的題,時間給的比較多,不需要過多的剪枝,直接暴力DFS就過了。
1 #include<iostream> 2 #include<string.h> 3 #include <algorithm> 4 5 using namespace std; 6 7 bool flag; 8 9 int a[25],t,sum,b[25]; 10 11 12 void DFS(int x,int y,intz) 13 { 14 if(flag) 15 return; 16 if(x==4) 17 flag=true; 18 if(flag) 19 return; 20 if(y==sum/4) 21 DFS(x+1,0,0); 22 if(flag) 23 return ; 24 for(int i=z;i<t;i++) 25 { 26 if(!b[i]&&y+a[i]<=sum/4) 27 { 28 b[i]=1; 29 DFS(x,y+a[i],i+1); 30 b[i]=0; 31 if(flag) 32 return ; 33 34 } 35 } 36 } 37 38 int main() 39 { 40 int n; 41 cin>>n; 42 while(n--) 43 { 44 cin>>t; 45 flag=false; 46 memset(a,0,sizeof(a)); 47 memset(b,0,sizeof(b)); 48 int f=1,max=0; 49 sum=0; 50 for(int i=0;i<t;i++) 51 { 52 cin>>a[i]; 53 sum+=a[i]; 54 if(a[i]>max) 55 max=a[i]; 56 } 57 if(sum%4||max>sum/4) 58 flag=false; 59 else 60 { 61 sort(a,a+t); 62 DFS(0,0,0); 63 } 64 if(flag) 65 cout<<"yes"<<endl; 66 else 67 cout<<"no"<<endl; 68 69 } 70 71 return 0; 72 }
HDU - 1518 :Square