Square
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 17776 | Accepted: 6160 |
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
题意:用给出的木棒拼出一个正方形出来
搜索弱爆了 最近在刷搜索 先从简单的开始 不过这题有一个剪枝还是蛮重要的
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; int n,m,ans,sum,edge; int num,flag; int a[25],vis[25]; bool judge() // 初始判断 总长度需要为4的倍数且 最大木棒长度要小于边长 { if(sum/4==sum*1.0/4.0&&a[n]<=sum/4) return true; return false; } void dfs(int s,int st) { int i,j; if(num==3) // 只要能组成三条边 就能构成正方形了 { flag=1; return ; } for(i=st;i>=1;i--) // 重要的剪枝 i从st开始循环 避免不成立的条件判断多次 { // 如 8 5 3 不成立 则搜到8 3时 如果再从n开始搜 则又会遇见8 3 5 的情况 if(flag==1) return ; // 如果已经满足条件 就可以return了 if(!vis[i]&&s+a[i]<=edge) { vis[i]=1; s+=a[i]; if(s==edge) { num++; dfs(0,n); num--; // 注意回溯 } else dfs(s,i-1); vis[i]=0; s-=a[i]; } } } int main() { int i,j,t; scanf("%d",&t); while(t--) { scanf("%d",&n); sum=0; for(i=1;i<=n;i++) { scanf("%d",&a[i]); sum+=a[i]; } if(!judge()) printf("no\n"); else { flag=num=0; sort(a+1,a+n+1); memset(vis,0,sizeof(vis)); edge=sum/4; dfs(0,n); if(flag) printf("yes\n"); else printf("no\n"); } } return 0; }