HDU 1518 Squre

Posted linda-

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 1518 Squre相关的知识,希望对你有一定的参考价值。

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


 1 #include <iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 int t,m,num[22],sum,target;
 7 bool vis[22];
 8 bool cmp(int a,int b)
 9 {
10     return a<b;
11 }
12 bool dfs(int sum,int cnt,int k)
13 {
14     if(cnt==3) return true;
15     for(int i=k;i>=1;i--)
16     {
17         if(vis[i]==0)
18         {
19             vis[i]=1;//递归的精髓就是回溯
20             if(sum+num[i]==target
21             {
22                 if(dfs(0,cnt+1,m)) return true;
23             }
24             else if(sum+num[i]<target)
25             {
26                 f(dfs(sum+num[i],cnt,i-1)) return true;
27             }
28             vis[i]=0;
29         }
30     }
31     return false;
32 }
33 int main()
34 {
35    // freopen("cin.txt","r",stdin);
36     scanf("%d",&t);
37     while(t--)
38     {
39         scanf("%d",&m);
40         sum=0;
41         for(int i=1;i<=m;i++) {
42             scanf("%d",&num[i]);
43             sum+=num[i];
44         }
45         memset(vis,0,sizeof(vis));
46         target=sum/4;
47         if(m<=3||sum%4!=0) puts("no");
48         else if(dfs(0,0,m)) puts("yes");
49         else puts("no");
50     }
51     return 0;
52 }

 

以上是关于HDU 1518 Squre的主要内容,如果未能解决你的问题,请参考以下文章

hdu 1518 Square

hdu1518-dfs

HDU1518:Square

HDU - 1518 :Square

DFS——hdu1518Square

hdu 1518(dfs)