您的位置:首页 > 其它

hdu 1518 Square (广搜)

2013-11-25 18:39 459 查看
[align=left]Problem Description[/align]
Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square?
 
 

[align=left]Input[/align]
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.
 
 

[align=left]Output[/align]
For each case, output a line containing "yes" if is is possible to form a square; otherwise output "no".
 
 

[align=left]Sample Input[/align]

3
4 1 1 1 1
5 10 20 30 40 50
8 1 7 2 6 4 4 3 5

 
 

[align=left]Sample Output[/align]

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         else
15         {return dfs(0,0,count+1);}
16     }
17     else
18     {
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 }


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: