hdu 1518 Square (广搜)

来源:互联网 发布:淘宝买东西怎么写评语 编辑:程序博客网 时间:2024/06/03 23:40
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
 
 
View Code
 1 #include<iostream> 2 using namespace std; 3  4 int num[30] , len; 5 int vis[30]; 6 int n , m; 7 int count; 8 int dfs(int start , int s , int count) 9 {10     if(s == len)11     {12         if(count == 3)   //跳出递归13         {return 1;}14         else15         {return dfs(0,0,count+1);}16     }17     else18     {19         int i;20         for(i = start ; i < m; i++)21         {22             if(vis[i]) continue;23             if(s + num[i] > len) continue;24             vis[i] = 1;25             if(dfs(i+1 , s + num[i] , count))26                 return 1;27             vis[i] = 0;28         }29     }30     return 0;31 }32 int main()33 {34     int i , sum , flag;35     cin>>n;36     while(n--)37     {38         sum = 0;39         cin>>m;40         count = 0;41         flag = 1;42         memset(vis , 0 , sizeof(vis));43         for(i = 0; i < m; i++)44         { 45             cin>>num[i];46             sum += num[i];47         }48         if(sum % 4) {cout<<"no"<<endl; flag = 0;}49         len = sum / 4;50         if(flag)51         {52             if(dfs(0 , 0 , 0))53                 cout<<"yes"<<endl;54             else cout<<"no"<<endl;55         }56     }57     return 0;58 }

 

原创粉丝点击