您的位置:首页 > 其它

hdu-1518-Square

2013-08-08 16:46 471 查看
题目大意:给你几组木棒,是否能围成正方形。注意减枝

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");
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: