DFS深度优先搜索(6)--hdu1455(经典深搜+剪枝)

                                                           Sticks

                                                                                  Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)



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


题意:有一堆的木棒,长度不一,它们是有一些整齐的木棒截断而成的,求最小的木棒原始长度。
思路很简单,深搜,但是直接深搜的话会tle,首先贪心一发,可以对木棒长度进行排序从大到小,优先使用长度长的木棒,加入当前长度不符合,考虑下一个木棒。然后就是几个剪枝;具体见代码注释:
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int n;
int a[65];
int vis[65];
int flag;
bool cmp(int a,int b)
{
	return a>b;
}
void Dfs(int lim,int sum,int cnt)   //lim指当前枚举的木棒长度   
{                                   //sum指拼凑出来的木棒长度  超过lim则减去lim 
	if(flag)return;                 //cnt指当前一共用了多少木棍 
	if(sum>lim) return;
	if(sum==lim&&cnt==n)
	{
		flag=1;
		return;
	}
	if(sum==lim)sum=0;
	int i;
	for(i=0;i<n;i++)
	{
		if(vis[i])continue;    //是否用过 
		vis[i]=1;
		Dfs(lim,sum+a[i],cnt+1);
		vis[i]=0;
		if(sum==0)return;
		//剪枝二:如果当前搜索时,前边的长度为0,而第一根没有成功的使用,
        //说明第一根始终要被废弃,所以这种组合必定不会成功
        //此处的剪枝必须有,因为这里的剪枝会节省很多的无用搜索,
		while(a[i]==a[i+1])i++;    //剪枝三:如果当前和上一次搜到的木棒是一样长的则没必要再搜一次了
	}

}
int main()
{
	int i,j,sum;
	while(scanf("%d",&n)!=EOF)
	{
		if(!n)break;
		memset(vis,0,sizeof(vis));
		sum=0;
		int Max=-1;
		for(i=0;i<n;i++)
		{
			scanf("%d",&a[i]);
			sum+=a[i];
		} 
		sort(a,a+n,cmp);  //将木棒按照长度从长到短的顺序排序
		for(i=a[0];i<=sum;i++)    //从木棒的最长的那根开始搜索,因为最小的组合也会大于等于最长的那根
		{
			flag=0; 
			if(sum%i==0)Dfs(i,0,0);  //剪枝一:如果不能被整除说明不能组成整数根木棒,搜下一个
			if(flag)break;
		}
		printf("%d\n",i);
	}
	return 0;
}





 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值