poj1011 Sticks

本文介绍了一种基于剪枝技术的算法,用于解决一个特定的问题,即从一系列切割后的木棍片段还原原始木棍的最短长度。通过输入切割后木棍的片段长度和数量,该算法能够高效地找出所有可能的原始木棍长度,并最终确定最小的可能长度。此技术在计算机科学领域中有着广泛的应用,特别是在优化问题和资源分配方面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

经典搜索题,需要很多剪枝。

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<string>
#include<algorithm>
using namespace std;
int a[100],vis[100],len,gen,n,ji;
bool cmp(int a,int b){
	return a>b;
}

int dfs(int t,int pos,int cha) //表示正在拼第t根,接下来从pos位置开始拼,拼完这根木棒还需多少长度 
{
	int i,j;
	if(cha==0){
		if(t==gen)return 1;
		for(i=1;i<=n;i++){
			if(!vis[i]){
				vis[i]=1;
				if(dfs(t+1,i+1,len-a[i]))return 1; //当前这根一定是剩下最长的一根,且一定要拼 
				vis[i]=0;break;
			}
		}
	}
	else{
		for(i=pos;i<=n;i++){
			if(i>1 && !vis[i-1] && a[i]==a[i-1])continue; //如果这根木棒和上一根木棒的长度相同,但是上一根没有成功,那么直接跳过这根 
			
			if(!vis[i] && a[i]<=cha){
				vis[i]=1;
				if(dfs(t,i+1,cha-a[i]))return 1;
				vis[i]=0;
				if(a[i]==cha)break; //如果当前这根木棒的长度恰好等于所差的长度,但是搜索不成功,那么就一定不能。 
			}
		}
	}
	return 0;
}

int main()
{
	int m,i,j,flag,sum;
	while(scanf("%d",&n)!=EOF && n!=0)
	{
		sum=0;ji=0;
		for(i=1;i<=n;i++){
			scanf("%d",&a[i]);
			if(a[i]&1)ji++;
			sum+=a[i];
		}
		if(i==1){
			printf("%d\n",sum);continue;
		}
		sort(a+1,a+1+n,cmp);  //从大到小排列 
		flag=0;memset(vis,0,sizeof(vis));
		for(len=a[1];len<=sum/2;len++){
			if(sum%len==0){ //必须要整除才行 
				gen=sum/len;
			    if(len&1){   //如果总长度是奇数,但个数小于总根数,那么直接下一个循环 
    				if(ji<gen)continue;
    			}
    			if(~len&1){  //如果总长度是偶数,但是有奇数个奇数,那么直接下一个循环 
			    	if(ji&1)continue;
			    }
				if(dfs(1,1,len)){
					flag=1;printf("%d\n",len);break;
				}
			}
		}
		if(!flag)printf("%d\n",sum);
	}
	return 0;
}



            

转载于:https://www.cnblogs.com/herumw/p/9464690.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值