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<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int q[22];
int vis[22];
int cmp(int a,int b)
{
return a<b;
}
int t,n,s;
void dfs(int num,int k,int length) //num 是已完毕的边 k是 数组的位置 length是当前边的长度
{
if(t==1)
return ;
if(num==4)
{
t=1;
return ;
}
if(length==s)
{
dfs(num+1,0,0);
if(t==1)
return ;
}
for(int i=k; i<n; i++)
{
if(length+q[i]<=s&&vis[i]==0)
{
vis[i]=1;
dfs(num,i+1,length+q[i]);
vis[i]=0;
}
}
}
int main()
{
int m;
scanf("%d",&m);
while(m--)
{
t=0;
s=0;
scanf("%d",&n);
for(int i=0; i<n; i++)
{
scanf("%d",&q[i]);
s=s+q[i];
}
if(s%4!=0)
{
printf("no\n");
continue;
}
sort(q,q+n,cmp);
s=s/4;
if(q[n-1]>s)
{
printf("no\n");
continue;
}
dfs(0,0,0);
if(t==1)
printf("yes\n");
else
printf("no\n");
}
return 0;
}
标准的回溯 可惜 我没有看到这个问题 要运行数据
版权声明:本文博客原创文章,博客,未经同意,不得转载。