POJ 1011 Sticks

Sticks
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 109705 Accepted: 25147

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

Source

 
题意:
给定不同长度的木棍,求其可组成的相同长度的最短的木棍长度
 
代码:
#include<cstdio>
#include<cstring>
#include<cstdlib>

int stick[65];
bool visited[65];
int n,sum,max,init;

int cmp(const void *a,const void *b)
{
	return *(int *)b-*(int *)a;
}

bool search(int len,int s,int num)          //当前所接木棍总长度为len,从第s根木棍开始计算,已用n根木棍
{
	if(num==n) return true;

	int flag=-1;                            //剪枝:相同长度的木棍只搜索一次
	for(int i=s;i<n;i++)
	{
		if(visited[i] || flag==stick[i]) continue;

		visited[i]=true;
		if(len+stick[i]<init)
		{
			if(search(len+stick[i],i+1,num+1))
				return true;
		}
		else if(len+stick[i]==init)
		{
			if(search(0,0,num+1))
				return true;
		}
		visited[i]=false;
		flag=stick[i];
		if(len==0) return false;              //剪枝:构建新棒是,对于第一根木棍,其余的所有木棍都无法与其组合
		                                      //则说明该init长度不合适,不必继续往下搜索,直接返回上一层
	}
	return false;
}

int main()
{
	int i,flag;
	while(scanf("%d",&n)!=EOF && n)
	{
		sum=0;
		for(i=0;i<n;i++)
		{
			scanf("%d",&stick[i]);
			sum+=stick[i];
		}
		memset(visited,false,sizeof(visited));

		qsort(stick,n,sizeof(int),cmp);

		max=stick[0]; flag=0;
		for(init=max;i<=sum-init;init++)           //剪枝:若能在[max,sum-init]找到最短的init,该init必也是[max,sum]的最短
		{
			if(sum%init==0 && search(0,0,0))       //剪枝:init必为sum的约数
			{
				printf("%d\n",init);
				flag=1;
				break;
			}
		}
		if(flag==0) printf("%d\n",sum);
	}
	return 0;
}

思路:
与POJ 2362类似,但需考虑所组成木棍的长度

若init为所求的最短原始棒长,max为给定的木棍中最长的木棍,sum为这堆棒子的长度之和,那么init必定在范围[max,sum]中

深度搜索前需对木棍进行倒序排序

注意代码注释中的剪枝方法

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值