hdu1518之DFS

来源:互联网 发布:买本书自学数控编程 编辑:程序博客网 时间:2024/06/05 09:47

Square

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


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
 

Source
University of Waterloo Local Contest 2002.09.21 

题目大意:现在有m个木棍,如果他们能过拼成一个正方形,则输出yes,否则输出no。

题目分析:DFS实现吧,大体思路都写在了注释中。

代码:
#include <iostream>using namespace std;int T,n,sum,len,flag;int a[50],visit[50];void dfs(int n1,int tsum,int pos){    if(flag==1){            //已经搜到了解决方案,则不用再搜了        return;    }      if(n1==4){              //如果4条边都已完成,则代表可以拼成1个正方形        flag=1;        return;    }    if(tsum==len){        dfs(n1+1,0,0);          //如果边长达到要求则已完成的边加1    }    for(int i=pos;i<n;i++){         //每次从pos开始搜,因为前面的数肯定不满足条件        if(!visit[i]&&tsum+a[i]<=len){            visit[i]=1;             //不被自己重复搜到            dfs(n1,tsum+a[i],i+1);                 visit[i]=0;              //可被别人搜到        }    }}int main(){    cin>>T;    while(T--)    {        flag=0;        cin>>n;        sum=0;        for(int i=0;i<n;i++){            visit[i]=0;            cin>>a[i];            sum+=a[i];        }        if(sum%4!=0){           //如果不能平均分成4条边的长度,则直接输出no            cout<<"no"<<endl;            continue;        }        len=sum/4;        for(int i=0;i<n;i++){      //如果有一个值大于平均值,则肯定不满足            if(a[i]>len){                flag=1;                break;            }        }        if(flag){            cout<<"no"<<endl;            continue;        }        dfs(0,0,0);        if(flag){            cout<<"yes"<<endl;        }        else{            cout<<"no"<<endl;        }    }    return 0;}


原创粉丝点击