1. 程式人生 > >hdu-1518-Square

hdu-1518-Square

題目大意:給你幾組木棒,是否能圍成正方形。注意減枝

Square

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


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
#include <stdio.h>
int sum,num,flag,n;
int visit[25],sti[25];
void DFS(int a,int b,int c)
{
    int i;
    if(a==num)
    {
        c++;
        if(c==4)
        {
            flag=1;
            return ;
        }
        a=0,b=0;
    }
    if(flag)
    return ;//我原來沒有這步,一直超時
    for(i=b; i<n; i++)
    {
        if(!visit[i])
        {
            if(a+sti[i]>num)
                continue;
            visit[i]=1;
            DFS(a+sti[i],i,c);
            visit[i]=0;
        }
    }
}
int main()
{
    int k,i,max;
    scanf("%d",&k);
    while(k--)
    {
        sum=-1;
        sum=0;
        scanf("%d",&n);
        for(i=0; i<n; i++)
        {
            scanf("%d",&sti[i]);
            if(sti[i]>max);
            max=sti[i];
            visit[i]=0;
            sum+=sti[i];
        }
        num=sum/4;
        if(sum%4!=0||n<4||num<max)
        {
            printf("no\n");
        }
        else
        {
            flag=0;
            DFS(0,0,1);
            if(flag)
                printf("yes\n");
            else
                printf("no\n");
        }
    }
}