N根木棒 能否拼成正方形
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 <cstdio> 2 # include <cmath> 3 # include <iostream> 4 # include <cstring> 5 # include <algorithm> 6 using namespace std ; 7 8 int n,sum,l; 9 int a[30],vis[30]; 10 int flag; 11 12 bool cmp(int x , int y) 13 { 14 return x > y ; 15 } 16 17 void dfs(int bian,int l,int k) //已完成的边数 当前边的长度 18 { 19 int i; 20 if(bian==4) 21 { 22 flag = 1; 23 return ; 24 } 25 if(l == sum) 26 { 27 if(flag) 28 return ; 29 dfs(bian+1,0,0); 30 } 31 for(i = k; i<n; i++) 32 { 33 if(!vis[i] && l+a[i]<=sum) 34 { 35 if(flag) 36 return; 37 vis[i] = 1; 38 dfs(bian,a[i]+l,i+1); 39 vis[i] = 0; 40 } 41 } 42 } 43 44 int main() 45 { 46 int t; 47 scanf("%d",&t); 48 while(t--) 49 { 50 int i; 51 sum = 0; 52 scanf("%d",&n); 53 for(i = 0; i<n; i++) 54 { 55 scanf("%d",&a[i]); 56 sum+=a[i]; 57 } 58 if(sum%4!=0) 59 { 60 printf("no\n"); 61 continue; 62 } 63 sum = sum/4; 64 65 for(i = 0; i<n; i++) 66 { 67 if(a[i]>sum) 68 break; 69 } 70 if(i!=n) 71 { 72 printf("no\n"); 73 continue; 74 } 75 sort(a,a+n,cmp) ; //从大到小排序可以减小耗时 76 77 memset(vis,0,sizeof(vis)); 78 flag = 0; 79 dfs(0,0,0); 80 if(flag) 81 printf("yes\n"); 82 else 83 printf("no\n"); 84 } 85 86 return 0; 87 }
时间: 2024-10-13 00:27:14