HDU-1518

Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square? 
InputThe 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. 
OutputFor 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
题意:给你一组数据,判断是否可将他们通过首尾相连成正方形。

题解:首先判断这些数相加除以4是否为整数,这些数中的最大值是否大于平均值及木棍个数是否多于四,不满足其中一个都输出no。然后,就是用DFS搜索了;

AC代码为:

#include<cstdio>
#include<iostream> 
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
int a[250],vis[250];
int N, M,length;


int DFS(int counter,int temp,int len)//len表示当前长度
{
if (counter == 3)
{
return 1;
}
for (int i = temp; i >= 0; i--)
{
if (!vis[i])
{
vis[i] = 1;
if (len + a[i] < length)
{
if( DFS(counter, i - 1, len + a[i]) )
return 1;
}
if (len + a[i] == length)
{
if (DFS(counter + 1, M - 1, 0))
return 1;
}
vis[i] = 0;
}
}
return 0;
}
int main()
{
int sum,flag;
cin >> N;
while (N--)
{
cin >> M;
memset(vis, 0, sizeof(vis));
sum = 0;
flag = 0;
for (int i = 0; i < M; i++)
{
cin >> a[i];
sum += a[i];
}
sort(a, a + M);
length = sum / 4;
if (length * 4 != sum || M<4 || length<a[M-1])
{
cout << "no" << endl;
continue;
}

if(DFS(0, M - 1, 0))
cout << "yes" << endl;
else
cout << "no" << endl;


}
return 0;
}



posted @ 2018-01-29 20:05  StarHai  阅读(222)  评论(0编辑  收藏  举报