1011. Sticks(木棒) -POJ

Sticks
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 110042 Accepted: 25243

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
推荐指数:※※※※
来源:http://poj.org/problem?id=1011
经典的剪枝问题。
1.以棒子(箱子)的条数为主干,搜索。
2.去掉肯定不能装的,不能整除。
3.去掉相同长度的重复计算。
4.去掉相同状态下的重复计算。
#include <iostream>
#include<string.h>
#include<string>
#include<sstream>
#include<algorithm>
using namespace std;
int compare_int(const void *a,const void *b){
	int *num_1=(int*)a;
	int *num_2=(int*)b;
	return (*num_2)-(*num_1);
}
int parts_num;
int *parts;
double capacity;
bool *visit;
bool dfs(int curr,int last_sum){//the capacity of current bin, the remain capacity of sum
	if(curr==capacity)
		return dfs(0,last_sum);
	if(last_sum==0)
		return true;
	int i;
	bool seen=false;
	for(i=0;i<=parts_num-1;i++){
		if(false==visit[i]){
			if(curr==0&&seen)
				return false;
			if(i-1>0&&parts[i]==parts[i-1]&&visit[i-1]==false)
				continue;
			if(curr+parts[i]<=capacity){
			visit[i]=true;
			if(dfs(curr+parts[i],last_sum-parts[i])==false)
				visit[i]=false;
			else
				return true;
			}
			seen=true;
		}
	}
	if(i==parts_num)
		return false;
}
int main()
{
	while(cin>>parts_num&&parts_num>0){
		parts=new int[parts_num];
		visit=new bool[parts_num];
		int i,sum;
		for(i=0;i<=parts_num-1;i++){
			cin>>parts[i];
		}
		qsort(parts,parts_num,sizeof(int),compare_int);
		sum=0;
		for(i=0;i<=parts_num-1;i++)
			sum+=parts[i];
		for(i=parts_num;i>=1;i--){
			if(sum%i==0&&sum/i>=parts[0]){
				memset(visit,0,parts_num*sizeof(bool));
				capacity=sum/i;
				if(true==dfs(0,sum)){
					cout<<capacity<<endl;
					break;
				}
			}
		}	
	}	
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值