Problem A: Problem C: Square
Time Limit:1 Sec Memory Limit:128 MB
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
分析:
题目大意为给定一组不同长度的棍子,判断是否能够组成一个正方形,每组棍数[4,20],每根棍长(0,10000]
也就是是否能用给定棍子组成四根相同长度的棍子
思路:用DFS枚举所有组合方式,直至找到符合的组合或无法找到
优化:
1、将棍子按长度排序,以避免重复或遗漏
2、将棍子按长度降序排列,当某一根棍子满足时就不必再试更短的棍子,直接进行下一步
3、(剪枝)正方形边长为棍子总长度的1/4,正方形边长不是整数的或者边长小于最长棍子长度的不用枚举
4、(剪枝)能组成三根棍子即满足条件
5、已组合的棍子标记为已访问
#include <iostream>
#include <algorithm>
#include<cstring>
using namespace std;
int m, sum, k, True, n;
int M[22];
bool sign[22];
bool dfs(int , int , int );
inline bool cmp(int x, int y)
{
return x>y;
}
int main()
{
cin >> n;
while (n--)
{
sum = 0;
memset(M, 0, sizeof(M));
memset(sign, false, sizeof(sign));
cin >> m;
for (int i = 0; i<m; i++)
{
cin >> M[i];
sum += M[i];
}
sort(M, M + m, cmp);//降序
k = sum / 4;
if (sum%4==0&&M[0]<=k&&dfs(0, 0, 0)) cout << "yes" << endl;
else cout << "no" << endl;
}
return 0;
}
bool dfs(int num, int len, int counts)
{
if (counts == 3) { return true; }
if (len == k) return dfs(0, 0, counts + 1);
for (int i = num; i<m; i++)
{
if (!sign[i] && M[i] + len <= k)
{
sign[i] = true;
if (dfs(i + 1, len + M[i], counts)) return true;
sign[i] = false;
}
}
return false;
}