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<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int sum;
int data[22],vis[22];
int m;
int dfs(int temp,int time,int y)
{
if(time==3) return 1;
int len=sum/4;
for(int i=y;i>=0;i--)
{
if(!vis[i])
{
vis[i]=1;
if(temp+data[i]==len)
{
if(dfs(0,time+1,m)) return 1;
}
else if(temp+data[i]<len)
{
if(dfs(temp+data[i],time,i-1)) return 1;
}
vis[i]=0;
}
}
return 0;
}
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
sum=0;
scanf("%d",&m);
for(int i=0;i<m;i++)
{
scanf("%d",&data[i]);
sum+=data[i];
}
sort(data,data+m);
memset(vis,0,sizeof(vis));
if(sum%4==0&&data[m-1]<=sum/4&&m>=4)
{
if(dfs(0,0,m-1)) printf("yes\n");
else printf("no\n");
}
else printf("no\n");
}
return 0;
}