扩大
缩小

hduoj 1518square


Square

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


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>
#include<algorithm>
using namespace std;
#define maxn 25
int str[maxn];
bool vis[maxn];
int n,sum;
bool cmp(int a,int b)
{
    return a>b;
}
bool dfs (int bianshu,int t,int s)
{
    if(bianshu==3)return true;
    for(int i=s;i<n;i++)
    {
        if(vis[i])continue;
        vis[i]=true;
        if(t+str[i]<sum)
        {
            if(dfs(bianshu,t+str[i],i))return true;
        }
        if(t+str[i]==sum)
        {
            if(dfs(bianshu+1,0,0))return true;
        }
        vis[i]=false;
    }
    return false;
}
int main()
{
    int ncase;
    scanf("%d",&ncase);
    while(ncase--)
    {
        scanf("%d",&n);
     sum=0;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&str[i]);
            sum+=str[i];
        }
        if(sum%4!=0){printf("no\n");continue;}

        else
        {
            sum/=4;
            memset(vis,0,sizeof(vis));
            sort(str,str+n,cmp);
            if(dfs(0,0,0))printf("yes\n");
            else
                printf("no\n");

        }
    }
    return 0;
}

 

posted on 2013-05-07 19:13  LinuxPanda  阅读(200)  评论(0编辑  收藏  举报

导航