[关闭]
@Chilling 2017-01-16T16:20:00.000000Z 字数 1188 阅读 905

HDU-1518: Square

搜索


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根木棒要用完。


  1. #include<stdio.h>
  2. #include<algorithm>
  3. #include<string.h>
  4. using namespace std;
  5. int a[111],ave,l,n,ans;
  6. int vis[111];
  7. void dfs(int l,int count,int pos)//当前边长度,边数,当前搜索的位置
  8. {
  9. if(l>ave||ans==1) return; //如果当前长度大于ave则不可行
  10. if(count==3)
  11. {
  12. ans=1;
  13. return;
  14. }
  15. if(l==ave) //该边长度满足
  16. {
  17. count++;
  18. l=0; //重置l与pos,开始下一边搜索
  19. pos=n-1;
  20. }
  21. for(int i=pos;i>=0;i--)
  22. {
  23. if(vis[i]==0) //如果该木棒未被使用过
  24. {
  25. vis[i]=1;
  26. dfs(l+a[i],count,i-1);
  27. vis[i]=0; //回溯
  28. }
  29. }
  30. }
  31. int main()
  32. {
  33. int t,i,sum;
  34. scanf("%d",&t);
  35. while(t--)
  36. {
  37. memset(a,0,sizeof(a));
  38. memset(vis,0,sizeof(vis));
  39. sum=0,l=1,ans=0;
  40. scanf("%d",&n);
  41. for(i=0;i<n;i++)
  42. {
  43. scanf("%d",&a[i]);
  44. sum+=a[i];
  45. }
  46. sort(a,a+n);
  47. ave=sum/4;
  48. if(n<=3||sum%4!=0||a[n-1]>ave) //预处理
  49. printf("no");
  50. else
  51. {
  52. dfs(0,0,n-1);
  53. if(ans==1)
  54. printf("yes");
  55. else
  56. printf("no");
  57. }
  58. printf("\n");
  59. }
  60. return 0;
  61. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注