hdu 1518 Square 【dfs】

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1518

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


 

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

3
4 1 1 1 1
5 10 20 30 40 50
8 1 7 2 6 4 4 3 5

Sample output

yes
no
yes

题意:对于输入的m个数,经过一番整合(可以数相加),只要能够成正方形,就输出yes,否则输出no.

分析:深搜,终止条件是num==4,如果这一条件成立,则输出yes,否则输出no.

代码如下:

#include
#include
#include
using namespace std;
const int maxn = 101;
int a[maxn],vis[maxn],n,sum,flag,psum;
void DFS(int num,int len,int pos)
{
    if(num == 4) //因为是判断能不能够成正方形,所以若是=4,直接return
    {
        flag = 1;
        return ;
    }
    if(len == psum) //等于平均值,则说明有一个符合题意了,len和对应的pos重新置为0
    {
        DFS(num+1,0,0);
        if(flag)
            return;
    }
    for(int i=pos;i>t;
    while(t--)
    {
        memset(vis,0,sizeof vis);
        sum = 0;
        flag = 0;
        cin>>n;
        for(int i=0;i>a[i];
            sum += a[i];
        }
        if(sum%4 != 0) //不能被4整除,一定不能,相当于剪枝
        {
            puts("no");
            continue;
        }
        psum = sum/4;
        for(int i=0;i psum) //这个符合的话,肯定就不可能满足了
            {
                flag = 1;
                break;
            }
        }
        if(flag == 1)
        {
            puts("no");
            continue;
        }
        DFS(0,0,0);
        if(flag == 1)
            puts("yes");
        else
            puts("no");
    }
    return 0;
}

 

你可能感兴趣的:(DFS)