POJ1011 Sticks

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


题意:一开始有若干个一样长的木棒,一个人去把这些木棒随机砍成不同的长度,砍完之后又想将这些木棒还原,但并不知道这些木棒原来的长度和数量,给定n个被砍之后的木棒的长度,将其还原成若干个长度尽量短的木棒,求出木棒长度。

据说这是一道经典的搜索题,通过dfs和一些减枝来写。

从假定的长度逐渐递增进行搜索。

而减枝的内容和注意的几点为:

1.因为木棒的长度是不均匀的,所以拼成之后的木棒的长度一定是大于等于这些木棒的最长长度,小于等于这些木棒长度的总和。

2.木棒的长度是会被所有木棒长度总和整除的。

3.当一个木棒不能凑出这个长度的时候,和他相同长度的木棒也凑不出来。

4.DFS的参数列表为:假定的木棒长、拼成这个木棒长还需要多长、还剩下多少根木棒。当需要的长度和剩下的木棒都为0时,则这个木棒便是这么多。

5.因为求最小,所以从最小长度开始搜(即木棒中最长的)。


代码如下:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
#define N 100
int a[N],n,vis[N];
int cmp(int a,int b)
{
	return a>b;
}
int DFS(int len,int remain,int num)
{
	if(remain==0&&num==0) return len;
	if(remain==0) remain=len;
	for(int i=1;i<=n;i++)
	{
		if(vis[i]) continue;
		if(remain>=a[i])
		{
			vis[i]=1;
			if(DFS(len,remain-a[i],num-1))
			 return len;
			 vis[i]=0;
			 if(a[i]==remain||len==remain)
			 break;
			 while(a[i]==a[i+1])
			 i++;
		}
	}
	return 0;
}
int main()
{
    int i,j,sum,k;
    while(scanf("%d",&n),n)
    {
    	sum=0;
    	for(i=1;i<=n;i++){
		  scanf("%d",&a[i]);
          sum+=a[i];
	  }
	    sort(a+1,a+1+n,cmp);
      for(i=a[1];i<=sum;i++)
	  {
	  	memset(vis,0,sizeof(vis));
	  	if(sum%i==0)
	  	 { 
	  		 k=DFS(i,0,n);
	  		if(k) break;
		 }
	   } 
	   cout<<k<<endl;
    }
	return 0;
}



  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值