http://poj.org/problem?id=2362
Square
| Time Limit: 3000MS | Memory Limit: 65536K | |
| Total Submissions: 16138 | Accepted: 5565 |
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
题意:有n条任意的木棒是否可以拼接成正方形。
不得不承认dfs的强大之处啊!!!!!!!!!!其中的思想真是太精华了。。
深搜的理念 : 能进则进, 进不了则换. 换不了则退.
深搜 :要多深有多深, 搜索 : 变向的枚举。
2》如果sum是4的倍数,记ave=su/4,如果M条木棍中有长度大于ave的木棍,则这M条木棍也不可能组成正方形.对于这两种情况,可以马上输出no,然后搜索,采用的搜索方式是搜索正方形的边,每次考虑往某一边上放木棍(还有一种搜索方式:搜索木棍,每次考虑将一条木棍放在一条边上),依次构造正方形的每条边,在构造时,从没有用过的木棍中选一条放在上面,如果选用这根木棍刚好构造这条边,则下一次继续构造下一条边,如果这根木棍的程度超过了ave,则要弃用这根木棍,如果加上这根木棍长度还没达到ave,则继续选用其它的木棍来构造这条边,一旦所有的边都可以成功构造,则输出yes,否则最后输出no. 对M跟木棍的长度进行排序后再搜索有利于加快搜索速度.
#include<iostream>
#include<algorithm>
using namespace std;
#define MAX 21
int n; //小棒总数
int average; //小棒的平均长度
int parts;//当前组合的原棒数
int max;//最长小棒的长度
int sum;
int a[MAX];//存储小棒相关信息
bool used[MAX]; //标记小棒是否使用
bool pt(int a,int b)
{
return a>b;
}
//cur_long: 当前长度
//tot: 找到几段木棒了
//I:为数组下标
bool dfs(int cur_long,int tot,int I)
{
int i;
if(tot==3)//剪枝3,已经有3条边满足条件最后一条边肯定满足因为最后一条边=sum-3*averge
return true;
for(i=I;i<n;i++)
{
if(i&&!used[i-1]&&a[i-1]==a[i])//剪枝4同样长度的木棍不行那么下一个与它一样长的木棒肯定不行
continue;// //当两根木棍相等时,如果前一根木棍没有选取,则后面一条木棍也不可能满足要求
if(!used[i])
{
if(cur_long+a[i]<average)
{
used[i]=true;
if(dfs(cur_long+a[i],tot,i+1))//还没构造好,继续选木棍
return true;
used[i]=false;
}
else if(cur_long+a[i]==average)
{
used[i]=true;
if(dfs(0,tot+1,0))//从0开始构造第tot+1条边
return true;
used[i]=false;
}
if(cur_long==0)
break;
}
}
return false;
}
int main()
{
int i,t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
sum=0;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum+=a[i];
used[i]=false;//初始清全部为false
}
sort(a,a+n,pt);//从大到小排序
average=sum/4;//求棒子的平均数
//parts=4;
if(n<4||sum%4!=0)//剪枝1
{
printf("no\n");
continue;
}
if(a[0]>average)//剪枝2
{
printf("no\n");
continue;
}
if(dfs(0,0,0))
printf("yes\n");
else
printf("no\n");
}
return 0;
}
#include<algorithm>
using namespace std;
#define MAX 21
int n; //小棒总数
int average; //小棒的平均长度
int parts;//当前组合的原棒数
int
int sum;
int a[MAX];//存储小棒相关信息
bool used[MAX]; //标记小棒是否使用
bool pt(int a,int b)
{
}
//cur_long: 当前长度
//tot: 找到几段木棒了
//I:为数组下标
bool dfs(int cur_long,int tot,int I)
{
}
int main()
{
}
探讨如何利用深度优先搜索解决正方形拼接问题,通过合理的剪枝策略提高算法效率。

1万+

被折叠的 条评论
为什么被折叠?



