回溯4 枝条拼接

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

题意就是给出N根枝条,问这些枝条可以拼成多少根长度相同的枝条且要长度最短的。

思路看大佬的都是剪枝??自己看了很久写不出,看大佬的代码也是啃了很久很久。。。才大概懂了。就是先将这些枝条从大到小排序,并且求出全部枝条的长度和,那么重点来了,这个符合的拼接后长度肯定在最大的枝条到枝条长度总和这个范围(max枝条<=min<=sum),min就是所求的拼接长度。

所以首先在主函数中就遍历max枝条到sum,如果sum%i==0说明这个长度可以被平均分,就代入dfs深搜;否则就跳过,下一个继续。

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

int n,sum,cnt;

struct node
{
	int length;
	int mark;
}stick[66];

bool cmp(node a,node b)
{
	return a.length>b.length;
}

//len表示当前木棒长度,count统计已经组成多少根了,
//l表示当前累加长度,pos表示当前标记到第几根 
int dfs(int len,int count,int l,int pos)
{
	if(len==sum) return 1;
	if(count==cnt) return 1;  //递归出口
	
	for(int i=pos;i<n;i++)
	{
		if(stick[i].mark) continue;
		if(len==(stick[i].length+l))
		{
			stick[i].mark=1;
            if(dfs(len,count+1,0,0))  return 1;
            stick[i].mark=0;
            return 0;
		}
		else if(len>(stick[i].length+l))
		{
			stick[i].mark=1;
			l+=stick[i].length;
			if(dfs(len,count,l,i+1)) return 1;
			
			l-=stick[i].length;
			stick[i].mark=0;
			if(l==0) return 0;
			while(stick[i].length==stick[i+1].length) i++;//这个剪枝 
			//如果不剪支跑一遍要140MS,加上剪支跑一遍只要31MS,ORZ
		}	
	}
	return 0;
	
 } 


int main(){	
	
	while(cin>>n&&n)
    {
    	
	cnt=sum=0;
	for(int i=0;i<n;i++)
	{
		cin>>stick[i].length;
		sum+=stick[i].length;
		stick[i].mark=0;
	}
	sort(stick,stick+n,cmp);
	

	for(int i=stick[0].length;i<=sum;i++)
	{
		if(sum%i) continue;
		cnt=sum/i;
		if(dfs(i,0,0,0))
		{
			printf("%d\n",i);
			break;
		}
	}
}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值