hdu1518Square

来源:互联网 发布:中文数据库 编辑:程序博客网 时间:2024/05/01 06:39

Square

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9583    Accepted Submission(s): 3126


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
 
 题目类型:深搜DFS

题意: 给你一堆木棒,你能否用这些木棒(全部用完)将其拼成一个正方形,

题解:说实话我第一次这个题目不知道怎么去写,因为当时没理解题意(就算理解了能不能A掉也当令说),他说的全部用完,哎 ,不说了,待会又要抱怨我的英语了,我看的 是网上的题解,最后按照他的题解去实现自己的代码,排序一下,大的在前,小的在后,节省时间,我刚开始dfs函数只有两个参数,一个是count,代表此时完成了有几条边,还有一个是x,代表当前木棍加起来的值,加起来等于每一条边的长度后(数据给出后长度是固定的,等于数据之和除以4,如果有余数,说明不能组成正方形),count+1;此时x便清零,继续搜索,发现交掉后超时;后来加上一个w作为记录数组下标的参数,就过了,我调试代码发现w还真是有作用:因为由于排序之后,大的在前面小的在后面,w作为一个标记,就会减少时间,从而不会超时,比如这样一组数据(排序后):
12 12(0) 10(1) 8(2) 6(3) 4(4) 4(5) 3(6) 3(7) 2(8) 2(9) 1(10) 1(11);括号内代表下标,12(0)跟2(8)组合,10(1)跟4(4)组合,8(2)跟6(3)组合,接下来注意w的作用了:4(5),x=4(5),不满足等于lengh,w=5,就会从下标为5那里往后去搜索,节省了时间;  

#include<iostream>#include<cstdio>#include<cstring>#include<cstdlib>using namespace std;int M,N;int visit[40],a[40];int flag;//标记int n;//每一组数据个数int lengh;//边长int cmp(const void *a,const void *b)//排序过后大的将会在小的前面,搜索起来耗得时间也少一些{return (*(int *)b - *(int *)a);}void dfs(int count,int x,int w)/*count代表边长数,x代表将那些边加起来等于lengh(x会一直逼近lengh,最后等于lengh);为什么要加一个w参数,*/{int i;if(x==lengh){x=0;w=0;count++;if(count==4){flag=1;return ;}}for(i=w;i<n;i++){if(!visit[i]&&x+a[i]<=lengh){visit[i]=1;dfs(count,x+a[i],i);visit[i]=0;}if(flag)return ;}}int main(){int T,sum,i;scanf("%d",&T);while(T--){memset(visit,0,sizeof(visit));sum=0;scanf("%d",&n);for(i=0;i<n;i++){scanf("%d",&a[i]);sum+=a[i];}if(sum%4!=0)//如果不能整除4,说明不能组成正方形,因为他要将木料全部用完{printf("no\n");continue;}qsort(a,n,sizeof(a[0]),cmp);lengh=sum/4;if(a[0]>lengh){printf("no\n");continue;}flag=0;//visit[0]=1;dfs(0,0,0);if(flag)printf("yes\n");elseprintf("no\n");}return 0;}/*312 1 1 2 2 3 3 4 4 6 8 10 12312 12 10 8 6 4 4 3 3 2 2 1 112 1 2 2 2 3 3 4 4 6 8 10 12  */


 

 

     

 
0 0