Square
问题描述 :
Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square?
输入:
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.
输出:
For each case, output a line containing “yes” if is is possible to form a square; otherwise output “no”.
样例输入:
3
4 1 1 1 1
5 10 20 30 40 50
8 1 7 2 6 4 4 3 5
样例输出:
yes
no
yes
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
const int maxn = 100;
using namespace std;
int maxx = 0;
int a[maxn];
int vis[maxn];
bool flag ;
int avg;
int n;
void dfs(int num,int len,int start)
{
if(num == 4)
{
flag = true;
return;
}
if(flag)
return;
if(len == avg )
{
dfs(num+1,0,0);
if(flag)
return;
}
for(int i = start; i < n;i++)
{
if(!vis[i]&&len+a[i]<=avg)
{
vis[i] =1;
dfs(num,len+a[i],i+1);
vis[i] = 0;
if(flag)
return;
}
}
}//成功的的变数,目前的长度,开始的位置
int main()
{
int t;
cin>>t;
for(int i = 0; i < t; i++)
{
int sum = 0;
maxx = 0;
cin>>n;
for(int j = 0; j < n; j++)
{
cin>>a[j];
if(a[j]>maxx)
maxx = a[j];
sum+=a[j];
}
avg= sum/4;
if(maxx >avg||sum%4!=0)
{
cout<<"no"<<endl;
continue;
}
sort(a,a+n);
memset(vis,0,sizeof(vis));
flag = false;
dfs(0,0,0);
if(flag)
cout<<"yes"<<endl;
else cout<<"no"<<endl;
}
return 0;
}