HDU1518 & POJ2362 & ZOJ1909 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


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

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

解决超时是关键!

AC代码:

 
 
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int a[25];
int n,averlen;
bool flag;
bool vis[25];
void DFS(int num,int len,int start)//成功边数,目前长度,开始位置
{
    if(flag)
        return ;
    if(num==4)
    {
        flag=true;
        return;
    }
    if(len==averlen)
    {
        DFS(num+1,0,0);
        if(flag)
            return ;
    }
    for(int i=start;i<n;i++)
    {
        if(!vis[i]&&len+a[i]<=averlen)
        {
            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];
        }
        averlen=sum/4;
        if(sum%4!=0||maxlen>averlen)
        {
            cout<<"no"<<endl;
            continue;
        }
        sort(a,a+n);
        memset(vis,false,sizeof(vis));
        flag=false;
        DFS(0,0,0);
        if(flag)
            cout<<"yes"<<endl;
        else
            cout<<"no"<<endl;
    }
    return 0;
}


你可能感兴趣的:(HDU1518 & POJ2362 & ZOJ1909 Square(DFS,剪枝是关键呀))