`
wangqisen
  • 浏览: 46767 次
文章分类
社区版块
存档分类
最新评论

搜索剪枝之1011

 
阅读更多

其实,搜索可以认为是DFS,递归穷举所有情况的同时,通过剪枝舍去那些不可能的情况,来降低搜索的复杂度。

Sticks
Time Limit:1000MS Memory Limit:10000K
Total Submissions:111462 Accepted:25581

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>
using namespace std;
int n[100001];
bool used[100001];
void sort(int a[],int num){
	for(int i=0;i<num-1;i++){
		for(int j=0;j<num-i-1;j++){
			if(a[j]<a[j+1]){
				int temp=a[j];
				a[j]=a[j+1];
				a[j+1]=temp;
			}
		}
	}
}
bool concate(int unused,int left,int targetLen,int totalNum){
	int i=0;
	if(left==0&&unused==0){
		return true;
	}else if(left==0){
		left=targetLen;
	}
	for(i=0;i<totalNum;i++){
		if(!used[i]){
			if(left<n[i])
				continue;
			left=left-n[i];
			used[i]=true;
			if(concate(unused-1,left,targetLen,totalNum))
				return true;
		}
	}
	used[i]=false;
	return false;
}
int main(){
	int sNum,sumLen=0;
	while(cin>>sNum){
		if(sNum==0)
			break;
		else{
			for(int i=0;i<100001;i++){
			used[i]=false;
			n[i]=0;
			}
			for(int i=0;i<sNum;i++){
				cin>>n[i];
				sumLen+=n[i];
			}
			sort(n,sNum);
			if(sNum==1){
				cout<<n[0]<<endl;
				continue;
			}
			for(int i=sumLen/n[0];(i>=2)&&(sumLen%i==0);i--){
				if(concate(sNum,sumLen/i,sumLen/i,sNum)){
					cout<<sumLen/i<<endl;
					break;
				}
			}
		}
		sumLen=0;
	}
}

顺便说下,并没有ac,但是,我测试了十来组数据,都是正确的,检查也看不出漏了哪些情况,所以,就这样贴上来吧
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics