描述
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<cstring>
#include<cstdlib>
using namespace std;
int stick[64];
int visited[64];
int L,N,last;
int st(int m,int n){
if(m == 0 && n == 0)
return 1;
if(m == 0){
m = L;
last = -1;
}
for(int i = last + 1;i < N; ++i){//因为按长度排好,所以从上一次比较过的位置开始减少不必要的重复。
if(!visited[i - 1] && stick[i] == stick[i - 1])//如果之前不成功,遇到相同长度可以直接跳过。
continue;
if(!visited[i] && stick[i] <= m){
visited[i] = 1;
last = i;
if(st(m - stick[i],n - 1))
return 1;
else{
visited[i] = 0;
if(stick[i] == m || m == L)//不成功的组合中,如果第一条或者最后一条不成功,该种枚举长度一定不成功,反证法:如果成功,那么一定存在某根组成的木棒中包含这些小木棒,这与实际矛盾,得证。
return 0;
}
}
}
return 0;
}
int cmp(const void *a,const void *b){
return *(int *)b - *(int *)a;
}
int main(){
int i,l,sum,max;
while(1){
scanf("%d",&N);
if(N == 0)
break;
sum = 0;
for(i = 0;i < N; ++i){
scanf("%d",stick + i);
sum += stick[i];
}
memset(visited,0,sizeof(int) * N);
qsort(stick,N,sizeof(int),cmp);//先选较长的木棒更易判断不成功的可能
max = stick[0];
for(L = max;L <= sum / 2; ++L){//枚举范围从最长的木棒开始到总长的一半,如果超出总长的一半,拼成一根即可
if(sum % L)
continue;
last = -1;
if(st(L,N)){
printf("%d\n",L);
break;
}
}
if(L > sum / 2)
printf("%d\n",sum);
}
return 0;
}
关键点就是抽象出枚举的状态——(需要拼的长度,剩余木棒数)。
总体思路就是枚举所有可能的初始长度,递归判断所有木棒能否组成该长度,递归出口就是需要拼的长度和剩余木棒均为0。
剪枝 \吐血。
经过试验这四个优化就够了:
棍子从大到小选择;
如果长度无法被总长整除,略过;
最开始的那根棍子不行就真的不行;
最后那根棍子不行就真的不行;
二刷:状态都写不出来。。。
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int n,len,vis[64],stick[64];
int uni(int num,int l){
if(num == 0 && l == 0)
return 1;
if(l == 0)
l = len;
for(int i = 0;i < n; ++i){
if(!vis[i] && l >= stick[i]){
vis[i] = 1;
if(uni(num - 1,l - stick[i]))
return 1;
else{
vis[i] = 0;
if(l == len || l == stick[i])//开始和最后的棍子
return 0;
}
}
}
return 0;
}
int main(){
int sum,i,j;
while(cin >> n && n){
sum = 0;
for(i = 0;i < n; ++i){
cin >> stick[i];
sum += stick[i];
vis[i] = 0;
}
sort(stick,stick + n,greater<int>() );
int half = sum / 2;
for(len = stick[0];len <= half; ++len){
if(sum % len)//不能整除的情况
continue;
memset(vis,0,sizeof(vis));
if(uni(n,len)){
cout << len << endl;
break;
}
}
if(len > half)
cout << sum << endl;
}
return 0;
}