HDU 1518 Square(深搜)

来源:互联网 发布:mac苹果商店打不开 编辑:程序博客网 时间:2024/06/06 08:30

题目:

Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square?

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.

For each case, output a line containing "yes" if is is possible to form a square; otherwise output "no"

Simple Input::

3

4 1 1 1 1

5 10 20 30 40 50

8 1 7 2 6 4 4 3 5

Simple Output:

yes

no

yes

题目分析:本题很容易理解,讲的是给n个数,试问这些数可不可以拼成一个正方形。本题可用dp或dfs,我选择用dfs,其中一个变量我用了全局,所以wa了好多次。。。。

#include<iostream>#include<cstdio>#include<cstring>#include<cstdlib>using namespace std;int n,m,sum,flag;int num[100],vis[100];int dfs(int e,int cnt,int p){    if(e==sum)//拼成边    {        e=0;        p=0;        cnt++;    }    if(cnt==4)    {        flag=1;        return 1;    }    for(int i=p;i<m;i++)//开始拼边    {        if(!vis[i])        {            vis[i]=1;            if(num[i]+e<=sum)            {                if(dfs(num[i]+e,cnt,i+1)==1)//迭代深搜                {                    return 1;//拼成返回真值                }            }            vis[i]=0;        }    }    return 0;}int main(){    scanf("%d",&n);    while(n--)    {        sum=0;        scanf("%d",&m);        for(int i=0;i<m;i++)//这里的i一定不能和dfs的i公用,在这里wa了好多次        {            scanf("%d",&num[i]);            sum+=num[i];        }        if(sum%4!=0)//剪枝,排除理论不可行的        {            printf("no\n");            continue;        }        memset(vis,0,sizeof(vis));        sum/=4;        flag=0;        flag=dfs(0,0,0);        if(flag)        {            printf("yes\n");        }        else        {            printf("no\n");        }    }    return 0;}


0 0
原创粉丝点击