HDU 1455 Sticks(DFS,剪枝,原来木棒的至少长度)

Sticks(答题)

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9115    Accepted Submission(s): 2700


Problem 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 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
 

Source
 



题意:

给我们一组凌乱的木棒,这些木棒是由一些相同长度的木棒切成的,让我们现在找出原先那些相同长度木棒至少多短。。。。


思路:

这样应该是属于比较繁琐的 DFS 了,剪枝(优化)少了容易超时。


代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#define MYDD 128

using namespace std;

int total,l;//给定木棒能够达到的组数,木棒的最小可能长度即答案
int n,sum;//木棒的个数,木棒总长度
struct Sti {
	int length;//长度
	int mark;//是否已经使用
} stick[MYDD];

bool cmp_length(Sti x,Sti y) {
	return x.length>y.length;//给定的木棒长度按照从长到短排序
}

int DFS(int s,int len,int location) {
	// s 已组成的木棒数目,len已达到的长度,location搜索木棒的下标位置
	if(s==total)
		return 1;
	for(int j=location+1; j<n; j++) {
		if(stick[j].mark)
			continue;//木棒已经用过
		if(len+stick[j].length==l) {
			stick[j].mark=1;
			if(DFS(s+1,0,-1))
				return 1;
			stick[j].mark=0;
			return 0;
		} else if(len+stick[j].length<l) {
			stick[j].mark=1;
			if(DFS(s,len+stick[j].length,j))
				return 1;
			stick[j].mark=0;
			if(len==0)//当前搜索,如果前面的len为0,但第一根没有用上,那么这根木棒就要舍弃
				return 0;
			while(stick[j].length==stick[j+1].length)
				j++;//剪枝:这根不满足,则长度相同的也不满足
		}
	}
	return 0;
}

int main() {
	while(scanf("%d",&n)&&n) {
		sum=0;
		for(int j=0; j<n; j++) {
			scanf("%d",&stick[j].length);
			sum+=stick[j].length;
			stick[j].mark=0;//标记木棒暂未使用
		}

		sort(stick,stick+n,cmp_length);

		for(l=stick[0].length; l<=sum; l++) {
			if(sum%l!=0)
				continue;//剪枝:如果不能够整除就没有整数解,换到下一个
			total=sum/l;//得到木棒总数目
			if(DFS(1,0,-1)) {
				//已经使用 1 个木棒,组成的长度为 0 ,从结构体数组下标 0 开始遍历
				printf("%d\n",l);
				break;
			}
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值