POJ2362_Square_深搜

来源:互联网 发布:阿里云虚拟主机 php7 编辑:程序博客网 时间:2024/06/01 23:17
Square
Time Limit: 3000MS Memory Limit: 65536KTotal Submissions: 24319 Accepted: 8378

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

34 1 1 1 15 10 20 30 40 508 1 7 2 6 4 4 3 5

Sample Output

yesnoyes

Source


大致题意:

给出数根已知长度的木棍,问把这些木棍都用上,能不能构成一个正方形。


大致思路:

先把木棍从大到小排序,然后进行带回溯的深搜。

三个剪枝:1)长度相等的木棍,前面的没用上,后面的就不用试了。2)拼一条边放的第一根木棍不行,说明这根木棍到最后也用不上,肯定不能拼成正方形。 3)拼同一条边的过程中,按从长到短的顺序放木棍。


解题过程:

WA了好几个小时,就因为两个语句写反了,导致拼好一条边后,这条边就不能被拆开了。


#include<cstdio>#include<algorithm>int stk [25];bool usd [25];int cas,n,sum;bool dfs (int now,int pos,int cpl){if(now==sum) now=0,pos=0,cpl++;if(cpl==4) return 1;for(int i=pos;i<n;i++){if(stk[i]+now>sum||usd[i]) continue;if(i>0&&stk[i]==stk[i-1]&&!usd[i-1]) continue;usd[i]=1;if(dfs(now+stk[i],i+1,cpl)) return 1;usd[i]=0;//超级超级超级WA点if(now==0) return 0;}return 0;}bool cmp (int x,int y){return x>y;}int main (){//freopen("in.txt","r",stdin);scanf("%d",&cas);while(cas--){scanf("%d",&n);sum=0;for(int i=0;i<n;i++){scanf("%d",stk+i);sum+=stk[i];}if(!(sum%4)) sum/=4;else{printf("no\n");continue;}std::sort(stk,stk+n,cmp);if(dfs(0,0,0)) printf("yes\n");else printf("no\n");for(int i=0;i<n;i++)usd[i]=0;}return 0;}


0 0
原创粉丝点击