Square
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
题意
给你一些长度不等的棍子,是否能把它们组成一个正方形,(全部用上)
分析
用深搜把每种组合都遍历一遍,然后找出符合条件的,关键是dfs(),里面的该用什么参数不好想的。
dfs(int sidesNumber ,int currentLength,int currentLocation)
sidesNumber:已经构成了几条边
currentLength: 当前正在构建边的长度
currentLocation: 正在构建边的位置
代码
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int stick[25];
int vis[25];
int op = 0, bianChang;
int m;
bool myCmp(int a, int b)
{
return a > b;
}
void dfs(int cur, int sum, int start)
{
if (cur == 3 || op == 1)
{
op = 1;
return ;
}
for (int i = start; i < m; i++)
{
if (vis[i] == 1)continue;
if (sum + stick[i] == bianChang)//已经构建成一条边
{
vis[i] = 1;
dfs(cur + 1, 0, 0);//边的数目加一,准备构建下一条边,
//所以下一条边的长度初始化为零,还要从0位置开始构建,
vis[i] = 0;
}
else if (sum + stick[i] < bianChang)//当前的边还没有构建完成,
{
vis[i] = 1;
dfs(cur, sum + stick[i], i + 1);
vis[i] = 0;
}
}
}
int main()
{
int n;
scanf("%d", &n);
while (n--)
{
scanf("%d", &m);
memset(stick, 0, sizeof(stick));
memset(vis, 0, sizeof(vis));
op = 0;
int sum = 0;
for (int i = 0; i < m; i++)
{
scanf("%d", &stick[i]);
sum += stick[i];
}
if (sum % 4 != 0 || m < 4)
{
printf("no\n");
continue;
}
sort(stick, stick + m, myCmp);
bianChang = sum / 4;
if (stick[0] > bianChang)
{
printf("no\n");
continue;
}
dfs(0, 0, 0);//已经构成边的数目,正在构建某一条边的当前长度,从某个棍子开始构建。
if (op == 1)
printf("yes\n");
else
printf("no\n");
}
return 0;
}
/*
3
4 1 1 1 1
5 10 20 30 40 50
8 1 7 2 6 4 4 3 5
*/
梦里不知身是客,一晌贪欢。