首页 > 代码库 > poj 2362

poj 2362

G - Square
Time Limit:3000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u
Submit Status Practice POJ 2362

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


dfs(be,len,cnt)

cnt==3 return true;
be代表当前选择第几个木棒,len,代表当前的长度

剪枝:
1.首先满足 sum%4==0
2.其次 最大边*4应该《=sum
3.当选择的木棒+当前的长度《=sum/4
AC无压力!
#include<iostream>#include<cstdio>#include<cstring>#include<string>#include<cmath>#include<algorithm>#include<cstdlib>#include<queue>#include<vector>#include<set>using namespace std;int t,n,a[10010],sum,maxx,side;bool flag;bool vis[10010];bool cmp(int x,int y){      return x<y;}void dfs(int be,int len,int cnt){      if(flag)            return ;      if(cnt==3)      {            flag=true;            return ;      }      if(len==side)            dfs(0,0,cnt+1);      for(int i=be;i<=n;i++)            if(!vis[i]&&len+a[i]<=side)            {                  vis[i]=true;                  dfs(i+1,len+a[i],cnt);                  if(flag)                        return ;                  vis[i]=false;            }}int main(){      scanf("%d",&t);      while(t--)      {            sum=0,maxx=0,flag=false;            memset(vis,0,sizeof(vis));            scanf("%d",&n);            for(int i=1;i<=n;i++)            {                  scanf("%d",&a[i]);                  sum+=a[i];                  maxx=max(maxx,a[i]);            }            side=sum/4;            sort(a+1,a+1+n,cmp);            if(sum%4!=0||maxx*4>sum)                  printf("no\n");            else            {                  dfs(0,0,0);                  if(flag)                        printf("yes\n");                  else                        printf("no\n");            }      }      return 0;}

  

poj 2362