菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
354
0

HDU-1518

原创
05/13 14:22
阅读数 20224

Given a set of sticks of various lengths, is it possible to join them end-to-end to form a square? 


3
4 1 1 1 1
5 10 20 30 40 50
8 1 7 2 6 4 4 3 5
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;
}



发表评论

0/200
354 点赞
0 评论
收藏