问题描述
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
思路:虽然知道是回溯+剪枝,但真的写起来头脑一头雾水
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<ctime>
#include<cstring>
using namespace std;
//clock_t start,end;
int n,stick[65],minlen,vis[65],maxlen,len,sum;
bool solve(int now,int cur,int cnt){
if(now==len){
int ncur=n;
//全部枚举完
if(cnt==sum/len){
cout<<len<<endl;
return true;
}
//继续枚举
while(vis[ncur]&&ncur>=0)ncur--;//找到最长的
vis[ncur]=1;
if(solve(stick[ncur],ncur,cnt+1))return true;
vis[ncur]=0;
//如果没有后面的不能拼凑完,当前方案不行
}
else{
for(int i=cur-1;i>=0;i--){
//遇到当前长度大于假设答案||当前长度跟前面的相等且前面的长度没用过||当前stick[i]已用过则不能用
if(now+stick[i]>len||(!vis[i+1] && stick[i]==stick[i+1])||vis[i])continue;
//凑成一根
if(now+stick[i]==len){
vis[i]=1;
if(solve(now+stick[i],i,cnt))return true;
vis[i]=0;
//后面的凑不成则当前方案不可行,回到前面的重新凑
return false;
}
//枚举拼凑
if(now+stick[i]<len){
vis[i]=1;
if(solve(now+stick[i],i,cnt))return true;
vis[i]=0;
//如果当前为拼凑的第一根且后面的凑不成,则该方案不行
if(!now)return false;
}
}
}
return false;
}
int main(){
// start=clock();
// freopen("input1.txt","r",stdin);
while((cin>>n)&&n){
sum=0;
for(int i=0;i<n;i++){
cin>>stick[i];
sum+=stick[i];
}
sort(stick,stick+n);
n=n-1;
minlen=stick[0];
maxlen=stick[n];
memset(vis,0,sizeof(vis));
vis[n]=1;
int i;
for(i=maxlen;i<sum;i++){
if(sum%i!=0)continue;
len=i;
// cout<<"len"<<len<<endl;
if(solve(maxlen,n,1))break;
}
if(i==sum)cout<<sum<<endl;
}
// end=clock();
// cout<<"time:"<<(double)(end-start)<<"ms"<<endl;
// fclose(stdin);
return 0;
}