poj1011Sticks(dfs+剪枝)

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.

Sample Input

9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0

Sample Output

6
5

题意: 现在有短枝参差不齐若干个,不知原长,不知原数量,求最短的原短枝长度(原短枝长度均相同)

思路: 搜索,将所有短枝从大到小排序求出MAX,则能出现的原短枝len必是处在(MAX,sum)之间,然后从大到小枚举短枝,搜索其与剩下所有的短枝匹配,若出现now_len==len的len,并且能让搜出的匹配数u=n时,则输出当前len

剪枝:剪除相邻长度相同且不能与前一len匹配的短枝,例如10,7,7,7,7 ,7,6,5。由于10与7匹配后不能满足now_len==len,则将后面所有的相同的短枝跳过搜索

代码:

   

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
int n,flag;
int a[70];
bool vis[70];
int cmp(int aa,int bb)
{
	return aa>bb;
}
//s是已经用掉的短枝数,u表示当前所在短枝的下标 
int len;
void dfs(int s,int now_len,int u)
{
	if(flag) return;
	if(now_len==0)
	{
		int k=0;
		while(vis[k]) k++;
		vis[k]=1;
		dfs(s+1,a[k],k+1);
		vis[k]=0;
		return;
	} 
	if(now_len==len)
	{
		if(s==n)
		{
			flag=1;
			return;
		}
		else dfs(s,0,0);
		return;
	}
	for(int i=u;i<n;i++)
	{
		if(!vis[i]&&now_len+a[i]<=len)
		{
			if(!vis[i-1]&&a[i]==a[i-1]) continue;//剪枝 
			vis[i]=1;
			dfs(s+1,now_len+a[i],i+1);
			vis[i]=0;
		}
	}
	return;
}
int main()
{
	while(cin>>n&&n)
	{
		int sum=0;
		for(int i=0;i<n;i++)
		{
			scanf("%d",&a[i]);
			sum+=a[i]; 
		}
	    sort(a,a+n,cmp);
		flag=0;
		//原短枝必在[a[0],sum)之间 
	    for(len=a[0];len<sum;len++)
	    {
	    	if(sum%len==0)//枚举能整除的len 
	    	{
	    	    memset(vis,0,sizeof(vis));
	    		dfs(0,0,0);
	    		if(flag) break;
			}
		}
		cout<<len<<endl;
	}
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小鱼爱吃火锅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值