HDU1518 Square(DFS,剪枝是关键呀)

Square

Time Limit : 10000/5000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 9   Accepted Submission(s) : 4
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
 

 

Source

University of Waterloo Local Contest 2002.09.21

 

题意:根据已知边的长度,问能否构成一个正方形.

解决超时是关键!

AC代码:

 

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int a[25];
bool vis[25];
int n,ave;
bool flag;
void dfs(int num,int len,int start)
{
    if(flag)
    return;
    if(num==4)
    {
        flag=true;
        return;
    }
    if(len==ave)
    {
        dfs(num+1,0,0);
        if(flag)
            return;
    }
    for(int i=start;i<n;i++)
    {
        if(!vis[i]&&len+a[i]<=ave)
        {
            vis[i]=true;
            dfs(num,len+a[i],i+1);
            vis[i]=false;
            if(flag)
                return;
        }
    }
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        cin>>n;
        int sum=0,maxlen=0;
        for(int i=0;i<n;i++)
        {
            cin>>a[i];
            sum+=a[i];
            if(a[i]>maxlen)
                maxlen=a[i];
        }
        ave=sum/4;
        if(sum%4!=0||maxlen>ave)
        {
            cout<<"no"<<endl;
            continue;
        }
        sort(a,a+n);
        memset(vis,0,sizeof(vis));
        flag=false;
        dfs(0,0,0);
        if(flag)
            cout<<"yes"<<endl;
        else
            cout<<"no"<<endl;
    }
}

 

 
posted @ 2016-07-19 10:40  俺叫王梦涵  阅读(825)  评论(0编辑  收藏  举报