0
点赞
收藏
分享

微信扫一扫

题目:POJ 1101 Sticks(DFS+剪枝)

Aliven888 2022-06-17 阅读 37

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.

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

int n, a[100], mark[100], mlen;
int cmp(int a, int b)
{
return a>b;
}
int dfs(int N, int now)
{
if (N==0 && now==0)
return 1;
if (now==0)
now=mlen;
for (int i=1; i<=n; i++){
if (!mark[i] && a[i]<=now){
if (i>1){
if (!mark[i-1] && a[i-1]==a[i])
continue;//上一个相同的棍子没通过,这个也不通过
}
mark[i]=1;
if (dfs(N-1, now-a[i])){
return 1;
}else{
mark[i]=0;
if (a[0]==now || now==mlen)
return 0;
}
}
}
return 0;
}
int main()
{
while (scanf("%d", &n)!=EOF && n){
int i, j, sum;
sum=0;
for (int i=1; i<=n; i++){
scanf("%d", &a[i]);
sum+=a[i];
}
sort(a+1, a+n+1, cmp);//由大到小排序
for (i=a[1]; i<=sum/2; i++){//最少两段
if (sum%i==0){//被整除说明可以组成长度为i的x个木棒
for (j=1; j<=n; j++)
mark[j]=0;//初始化
mlen=i;
if (dfs(n, mlen)){
printf("%d\n", mlen);
break;
}
}
}
if (i>sum/2)
printf("%d\n", sum);
}
return 0;
}


举报

相关推荐

0 条评论