Square
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 19982 | Accepted: 6955 |
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
Source
题目链接 :http://poj.org/problem?id=2362
题目大意 :有n个木条,问用这n个木条能不能拼出一个正方形
题目分析 :DFS+剪枝,这题是POJ 1011 那题的简单版,而且这题时间放的很宽,基本上小剪一下就可以过,笔者本着学习的态度写了不少剪枝,依旧跑了110ms,不知0ms大神是怎么做到的,若有大神知道还求指点
1.总长必须是4的倍数,否则无解
2.对木条从大到小排序,如果最长边大于总长的四分之一则无解,而且每次从长边开始选可以减少判断次数,因为长边的灵活度比较低,如果有一根长边用不上则无解
3.搜索时如果两根木条的长度相同,前一根没有选则后一根必然不会选
4.每次加之前判断加上是否会超过边长,若会超过则不选
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int const MAX = 21;
int stick[MAX];
int vis[MAX]; //标记木条是否用过
int num, side; //num表示木条数,side表示边长
bool flag;
//cur表示当前正在拼装的木条长度,other表示其他的木条,count表示拼成的边数
bool cmp(int a, int b)
{
return a > b;
}
bool DFS(int cur, int other, int count)
{
//如果当前长度等于边长,count加1,当前长和其他都置为0开始拼下一条边
if(cur == side)
{
count++;
cur = 0;
other = 0;
}
//如果count等于4,说明找到可行解,返回true
if(count == 4)
return true;
for(int i = other; i < num; i++) //枚举其他木条
{
//若两个木棒长度相同,前一个没用,则这一个也不会用
if(i && !vis[i-1] && stick[i] == stick[i-1])
continue;
//如果下一根未用且加上后长度小于边长
if(cur + stick[i] <= side && !vis[i])
{
vis[i] = 1; //标记为已使用
//如果当前方案能找到可行解则返回true
if(DFS(cur + stick[i], i + 1 , count))
return true;
//如果找不到,将改木条标记为未使用,供下一种方案使用
vis[i] = 0;
}
}
return false;
}
int main()
{
int n, sum;
scanf("%d",&n);
while(n--)
{
flag = false;
sum = 0;
memset(vis,0,sizeof(vis)); //木条初始化为未用
scanf("%d",&num);
for(int i = 0; i < num; i++)
{
scanf("%d",&stick[i]);
sum += stick[i];
}
sort(stick, stick+num, cmp); //将木条从小到大排序
//如果总长不是4的倍数或者最长边大于总长的四分之一则不可能拼成
if(sum % 4 || stick[0] > sum / 4)
{
printf("no\n");
continue;
}
side = sum / 4;
flag = DFS(0,0,0);
if(flag)
printf("yes\n");
else
printf("no\n");
}
}