1. 程式人生 > >hdu 1518 Square 【dfs】

hdu 1518 Square 【dfs】

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<iostream>
#include<algorithm>
#include<string.h>
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<n;i++) //遍歷每一種可能的情況,初始情況pos為0
    {
       if(!vis[i] && len + a[i] <= psum)
       {
           vis[i] = 1;
           DFS(num,a[i]+len,i+1);
           if(flag)
               return;
           vis[i] = 0; //回溯操作
       }
    }
}
int main()
{
    ios::sync_with_stdio(false);
    int t;
    cin>>t;
    while(t--)
    {
        memset(vis,0,sizeof vis);
        sum = 0;
        flag = 0;
        cin>>n;
        for(int i=0;i<n;i++)
        {
            cin>>a[i];
            sum += a[i];
        }
        if(sum%4 != 0) //不能被4整除,一定不能,相當於剪枝
        {
            puts("no");
            continue;
        }
        psum = sum/4;
        for(int i=0;i<n;i++)
        {
            if(a[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;
}