HDU 1518 Square 【经典DPS】

Square

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


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
 


题解:在给出的M个数进行组合,如果能组成一个正方形 即可输出yes 否则输出no

注意:

1:第一次做超时,是因为对M个数进行了排序(为了找出最大的一个数),其实不用 DFS已经把所有情况遍历

 

#include<stdio.h>
#include<stdbool.h>
#include<string.h>
int nn,b,vis[30],a[30],sum,Nbian,flag;
void DFS (int l,int b,int s)//l指成立边的条数 b搜索第B个数 第B个数是S
{
    if(l==5)//l=5时,说明前四条边找成功,可以结束搜索
    {
        flag=1;
        return ;
    }
    for(int i=b+1; i<=nn; i++)
    {
        if(vis[i]==false)
        {
            if(s+a[i]<=sum/4)
            {
                vis[i]=true;
                if(s+a[i]==sum/4)//相等时 一条边形成 搜索下一层
                {
                    DFS(l+1,0,0);
                }
                else
                {
                    DFS(l,i,s+a[i]);//小于边长 循环再搜索
                }
                if(flag==1)
                {
                    return ;
                }
                vis[i]=false;
            }
        }
    }}
int main (void)
{
    int i,n,ii,max;

    scanf("%d",&n);
    while(n--)
    {
        max=0;
        flag=0;
        memset(vis,0,sizeof(vis));
        memset(a,0,sizeof(a));
        sum=0;
        scanf("%d",&nn);
        for(i=1; i<=nn; i++)
        {
            scanf("%d",&a[i]);
            sum=sum+a[i];
            if(a[i]>max)//优化找最大值,不用排序了节约时间
            max=a[i];
        }
        if(sum%4!=0)//无法构成四个边等长的情况no
        {
            printf("no\n");
            continue;
        }
        if((sum/4)<max)//最大的一个数比边长大 no
        {
            printf("no\n");
            continue;
        }
        DFS(1,0,0);//边,第一个数,第一个数的值
        if(flag) printf("yes\n");
        else printf("no\n");
    }
    return 0;
}


 

你可能感兴趣的:(ACM,HDU)