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
给出几条线段,判断是否能组成一个正方形。
可以知道边长是总长的1/4,先将线段从大到小排序,每层取一条,放得下则下层再从比它小的线段找,避免重复,组成一条边后清零,从头在没有取走的继续找,直到组成三条,剩下必定能组成第四条。
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int vis[30];
int a[30];
int q,n;
bool ss(int cot,int i,int len){
if(cot==3){
return true;
}else{
for(int j=i;j<n;j++){
if(!vis[j]){
if(a[j]==len){
vis[j]=1;
if(ss(cot+1,0,q)){
return true;
}
}else if(a[j]<len){
vis[j]=1;
if(ss(cot,j+1,len-a[j])){
return true;
}
}
vis[j]=0;
}
}
}
return false;
}
int main()
{
int T,i,s;
cin>>T;
while(T--){
cin>>n;
s=0;
memset(vis,0,sizeof(vis));
for(i=0;i<n;i++){
cin>>a[i];
s+=a[i];
}
sort(a,a+n);
if(s%4!=0){
cout<<"no"<<endl;
}else{
q=s/4;
if(ss(0,0,q)){
cout<<"yes"<<endl;
}else{
cout<<"no"<<endl;
}
}
}
return 0;
}