#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
int len[20],sum,M;
bool flag,f[20];//flag标记是否找到
void dfs(int d,int stick,int nowlen)
{
//i:正在处理的小棍,stick:已经拼好的边框数,nowlen:当前正在拼的框的长度
int j;
if(flag||stick>2)
{
if(stick>2)
flag=1;//已经拼好3个框,第四个不用拼了
return ;
}
else
{
for(j=d;j<M;j++)
{
if((!f[j])&&nowlen+len[j]<=sum)
{
f[j]=1;//标记
if(nowlen+len[j]==sum)
dfs(0,stick+1,0);//拼好了一个,继续拼下一个
else
dfs(j+1,stick,nowlen+len[j]);//继续拼当前的
f[j]=0;//恢复标记
}
}
}
}
int main()
{
int ca,i,j;
scanf("%d",&ca);
while(ca--)
{
scanf("%d",&M);
for(i=sum=0;i<M;i++)
{
scanf("%d",&len[i]);
sum+=len[i];
}
if(sum%4!=0)
{
printf("no\n");
continue;
}
sum/=4;
for(int i=0;i<M;i++)
for(int j=i+1;j<M;j++)
{
if(len[i]<len[j])
{
int t=len[i];
len[i]=len[j];
len[j]=t;
}
}
if(len[0]>sum)
{
printf("no\n");
continue;
}
flag=0;
dfs(0,0,0);
printf("%s\n",flag?"yes":"no");
}
//system("pause");
return 0;
}
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".
Sample Input
3
#include <stdio.h>
int a[20];
int sum=0;
int b[20]={0};
int n;
int flag=0;
void fun(int step,int num,int toile)
{
if(num>2)
{
flag=1;
}
for(int i=step;i<n;i++)
{
if((!b[i])&&(toile+a[i]<=sum))
{
b[i]=1;
if(toile+a[i]==sum)
{
fun(0,num+1,0);
}
else
{
fun(i+1,num,toile+a[i]);
}
b[i]=0;
}
}
}
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
if(sum%4==0)
{
sum=sum/4;
fun(0,0,0);
}
else
{
printf("NO");
}
if(flag==1)
printf("YES");
return 1;
}
#include <stdio.h> int a[20]; int sum=0; int b[20]={0}; int n; int flag=0; void fun(int step,int num,int toile) { if(num>2) { flag=1; } for(int i=step;i<n;i++) { if((!b[i])&&(toile+a[i]<=sum)) { b[i]=1; if(toile+a[i]==sum) { fun(0,num+1,0); } else { fun(i+1,num,toile+a[i]); } b[i]=0; } } } int main() { scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d",&a[i]); sum=sum+a[i]; } //先排序 for(int i=0;i<n;i++) for(int j=i+1;j<n;j++) { if(a[i]>a[j]) { int t=a[i]; a[i]=a[j]; a[j]=t; } } if(sum%4==0) { sum=sum/4; fun(0,0,0); } else { printf("NO"); } if(flag==1) printf("YES"); return 1; }
4 1 1 1 1 5 10 20 30 40 50 8 1 7 2 6 4 4 3 5
Output for Sample Input
yes no yes