dfs Square poj 2362

来源:互联网 发布:痘印 红 知乎 编辑:程序博客网 时间:2024/05/21 04:43
Square
Time Limit: 3000MS Memory Limit: 65536KTotal Submissions: 20988 Accepted: 7314

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

34 1 1 1 15 10 20 30 40 508 1 7 2 6 4 4 3 5

Sample Output

yesnoyes

Source

Waterloo local 2002.09.21

#include<iostream>#include<cstdio>#include<cstring>#define maxn 50001#include<algorithm>using namespace std;int a[maxn],vis[maxn],l,n,flag;void dfs(int num,int len,int pos){    if(num==4)    {        flag=1;        return;    }    if(len==l)    {        dfs(num+1,0,n-1);    }    for(int i=pos;i>=0;i--)    {        if(!vis[i]&&len+a[i]<=l)        {            vis[i]=1;            dfs(num,len+a[i],i-1);            if(flag)            return;            vis[i]=0;        }    }}int main(){    int t,sum;    scanf("%d",&t);    while(t--)    {        flag=0;        sum=0;        memset(vis,0,sizeof(vis));        scanf("%d",&n);        for(int i=0;i<n;i++)        {            scanf("%d",&a[i]);            sum+=a[i];        }        sort(a,a+n);        l=sum/4;        if(sum%4!=0||l<a[n-1]||n<4)        {            printf("no\n");            continue;        }        dfs(0,0,n-1);        if(flag)            printf("yes\n");        else            printf("no\n");    }    return 0;}


#include<iostream>#include<cstdio>#include<cstring>#define maxn 5001#include<algorithm>using namespace std;int a[maxn],vis[maxn],l,n;int dfs(int num,int len,int pos){    if(num==3)        return 1;    for(int i=pos;i>=0;i--)    {        if(!vis[i])        {            vis[i]=1;            if(len+a[i]<l)            {               if(dfs(num,len+a[i],i-1))                return 1;            }            else if(len+a[i]==l)               if(dfs(num+1,0,n-1))                  return 1;                vis[i]=0;        }    }    return 0;}int main(){    int t;    scanf("%d",&t);    int sum;    while(t--)    {        memset(vis,0,sizeof(vis));        sum=0;        scanf("%d",&n);        for(int i=0;i<n;i++)        {            scanf("%d",&a[i]);            sum+=a[i];        }        sort(a,a+n);        l=sum/4;        if(n<4||sum%4!=0||l<a[n-1])        {            printf("no\n");            continue;        }        if(dfs(0,0,n-1)) printf("yes\n");        else printf("no\n");    }    return 0;}


0 0
原创粉丝点击