蓝桥杯 算法训练 Sticks

蓝桥杯 算法训练 Sticks

题目描述

  • 资源限制
    时间限制:1.0s 内存限制:999.4MB
  • 问题描述
    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.
  • 输入格式
    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.
  • 输出格式
    The output should contains the smallest possible length of original sticks, one per line.
  • 样例输入
    9
    5 2 1 5 2 1 5 2 1
    4
    1 2 3 4
    0
  • 样例输出
    6
    5

方案1 DFS 剪枝

#include<iostream>
#include<algorithm>

using namespace std;

int N;			//棍子的个数
int	sticks[64];	//sticks[i]: 第i+1个棍子的长度 
int sum;		//棍子长度之和 

//函数功能: 当前位置cur, 标志数组flag, 当前长度len, 目标长度target				
bool f(int cur, bool flag[], int len, int target){	
	//当前长度 = 目标长度,继续寻找下一个凑成target 
	if(len == target){
		//从仅剩的最大木棍开始凑 
		for(int i=N-1; i>=0; i--){
			//如果该木棍没有被使用 
			if(!flag[i]){
				flag[i] = true;	  	//使用该木棍 
				if(!f(i, flag, sticks[i], target)){
					flag[i] = false;
					return 0;
				}
				break; 
			}
		}
		return 1;
	}else if(len < target){			//当前长度 < 目标长度,继续寻找下一个凑成target 
		int last = 0;
		for(int i=cur-1; i>=0; i--){		//从当前位置向后找 
			if(!flag[i] && last!=sticks[i] && sticks[i] + len<=target){
				flag[i] = true;
				if(f(i, flag, sticks[i] + len, target)){
					return 1;
				}
				flag[i] = false;
				last = sticks[i];
				//	如果当前位置的木棍能局部凑成但整体失败,则以后位置也不可能成功 
				if(sticks[i] + len == target){
					return 0; 
				}
			}
		}
		return 0;	
	}else{
		return 0;
	}
}

int main(){	
	cin>>N;
	while(N){
		sum = 0;
		
		for(int i=0; i<N; i++){
			cin >> sticks[i];
			sum += sticks[i];
		}
		
		sort(sticks, sticks+N);
		
		for(int i=N; i>0; i--){
			bool flag[64] = {0};
			if((sum%i == 0) && f(N, flag, sum/i, sum/i)){
				cout<<sum/i<<endl;
				break;
			}
		}
		cin >> N;
	} 
	return 0; 
} 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值