HDU1518:Square(DFS)

来源:互联网 发布:sql中with as的用法 编辑:程序博客网 时间:2024/05/01 22:27
Problem 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
这道题,多处运用好检查旗子然后return的话,还是可以1s内AC的
#include<stdio.h>#include<string.h>int a[21],sum;int vis[21],m,flag;void dfs(int step,int len,int cur)//已经达成的边数,正在凑的长度,选择的木棒标号{if(step==3)//找到三根就行,剩下的一定能满足要求{flag=1;return;}if(len==sum){ dfs(step+1,0,0);if(flag)return;}for(int i=cur;i<m;++i)if(!vis[i]&&len+a[i]<=sum)//<span style="font-family: 'Courier New', Courier, monospace; white-space: pre-wrap;">就是忘了加</span><span style="font-family: 'Courier New', Courier, monospace; white-space: pre-wrap;">len+a[i]<=sum</span><span style="font-family: 'Courier New', Courier, monospace; white-space: pre-wrap;">这一步,让我WA好多次,唉还是要多修炼才行</span><span style="font-family: 'Courier New', Courier, monospace; white-space: pre-wrap;"></span>{vis[i]=1;dfs(step,len+a[i],i+1);if(flag)return;vis[i]=0;}}int check(int s){for(int i=0;i<m;++i)if(s<a[i]){puts("no");return 0;}return 1;}int main(){int n;scanf("%d",&n);while(n--){sum=0;scanf("%d",&m);for(int i=0;i<m;++i){scanf("%d",a+i);sum+=a[i];}if(sum%4!=0){puts("no");continue;}sum/=4;if(!check(sum))continue;memset(vis,0,sizeof(vis));flag=0;dfs(0,0,0);if(flag)puts("yes");elseputs("no");}return 0;}


0 0
原创粉丝点击