UVA - 307 Sticks(回溯+剪枝)


 Sticks 

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 file contains blocks of 2 lines. The first line contains the number of sticks parts after cutting. The second line contains the lengths of those parts separated by the space. The last line of the file contains zero.

Output

The output file 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


题目大意:乔治拿来一组等长的木棒,将它们随机地砍断,使得每一节木棍的长度都不超过50个长度单位。
然后他又想把这些木棍恢复到为裁截前的状态,但忘记了初始时有多少木棒以及木棒的初始长度。
请你设计一个程序,帮助乔治计算木棒的可能最小长度。每一节木棍的长度都用大于零的整数表示。


解析:下面说下几个重要的剪枝:
1.把所有木棍的长度从大到小排列,组合木棒时优先使用长的木棍,这样可以加快组合速度,并且对后面的剪枝有帮助。
2.在枚举原木棒长度时,枚举的范围为max与sum/2之间,如果这个区间内没有找到合适的长度,那么最后原木棒的长度只能是sum。
3.木棒的长度一定是所有木棍长度的和的约数。
4.当第i个木棒未选取时,如果i+1木棒与i木棒相同长度。跳过,没有必要重复考虑。
5.在深搜过程中,如果当前是在拼一根新木棒的第一截,但如果把可用的最长的一根木棒用上后不能拼成功的话,那么就不用再试后面的木棒了。


试想:失败说明现在使用stick[i]是不可行的,那么以后无论什么时候使用stick[i]都是不可行的,因为以后再处理stick[i]时可使用的木棍一定是当前可使用的木棍的子集,在更多木棍选择的情况下都不能组合成功,那么,在更少木棍选择的情况下一定不能组合成功。

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int N = 60;
int stick[N];
int vis[N];
int dis,tot;
bool ok;
int n;
bool cmp(int a,int b) {
	return a > b;
}
void dfs(int cur,int sum,int left) {
	if(cur == tot) {
		ok = true;
		return ;
	}
	if(ok) {
		return ;
	}
	for(int i = left; i < n; i++) {
		if(!vis[i]) {
			if(sum + stick[i] == dis) {
				vis[i] = true;
				dfs(cur+1,0,0);
				vis[i] = false;
				return ;
			}else if( sum + stick[i] < dis){
				vis[i] = true;
				dfs(cur,sum+stick[i],i);
				vis[i] = false;
				int j;
				for(j = i; j < n; j++) {
					if(stick[j] != stick[j+1]) {
						break;
					}
				}
				if( j == n || !sum || ok) {
					return;
				}
			}
		}
	}
}
int main() {
	while(scanf("%d",&n) != EOF && n) {
		int sum,maxa;
		sum = maxa = 0;
		for(int i = 0; i < n; i++) {
			scanf("%d",&stick[i]);
			sum += stick[i];
			maxa = max(maxa,stick[i]);
		}
		sort(stick,stick+n,cmp);
		ok = false;
		for(int i = maxa; i <= sum / 2; i++) {
			if( sum % i == 0) {
				tot = sum / i;
				dis = i;
				memset(vis,0,sizeof(vis));
				dfs(1,0,0);
				if( ok ) {
					break;
				}
			}
		}
		if(ok) {
			printf("%d\n",dis);
		}else{
			printf("%d\n",sum);
		}
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值