您的位置:首页 > 其它

深度优先搜索

2016-02-20 16:34 295 查看
Sticks poj 1011

Description

George took sticks of the same length and cut them randomly until all parts became at most 50 units long. Now he wants to return sticks to the original state, but he forgot how many sticks he had originally and how long they were originally. Please help him
and design a program which computes the smallest possible original length of those sticks. All lengths expressed in units are integers greater than zero.
Input

The input contains blocks of 2 lines. The first line contains the number of sticks parts after cutting, there are at most 64 sticks. The second line contains the lengths of those parts separated by the space. The last line of the file contains zero.
Output

The output should contains the smallest possible length of original sticks, one per line.
Sample Input
9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0

Sample Output
6
5

#include <cstdio>

#include <cstring>

#include <cstdlib>

#include <iostream>

#include <algorithm>

using namespace std;

const int maxn=70;

int n,sum,aim,num,a[maxn];

bool used[maxn];

int cmp(int x,int y)

{
if(x>y)
return 1;
return 0;



bool dfs(int Stick,int len,int pos)

{
int i;
bool sign=(len==0?true:false);
if(Stick==num)
return true;
for(i=pos+1;i<n;i++)
{
if(used[i]) continue;
if(len+a[i]==aim)  //正好完成组合
{
used[i]=true;   //标记第i根棍子被使用
if(dfs(Stick+1,0,-1))  //进入下一层搜索
return true;
used[i]=false;   //若下一层搜索失败则证明第i根棍子不应使用,所以要置false
return false;
}
else if(len+a[i]<aim)   //长度不够
{
used[i]=true;  //标记第i根棍子被使用
if(dfs(Stick,len+a[i],i))  //进入下一层搜索,已组合好的棍子长度变为len+a[i]
return true;
used[i]=false;
if(sign) return false;
while(a[i]==a[i+1]) i++;   //一个重要的剪枝
}
}
return false;

}

int main()

{
while(scanf("%d",&n)==1)
{
if(n==0) break;
sum=0;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum+=a[i];  //所有木棍的长度和是结果的上限
}
sort(a,a+n,cmp);    //对stick的长度降序排列(贪心策略)
for(aim=a[0];aim<=sum;aim++)   //枚举每种可能的木棍长度,最长为sum,最短为a[0]
if(sum%aim==0)
{
num=sum/aim;  //木棍的个数
memset(used,false,sizeof(used));  //每次都要初始化
if(dfs(1,0,-1))
{
printf("%d\n",aim);
break;
}
}
}
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: