HDU-1518
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 5Sample 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;
}