乔治拿来一组等长的木棒,将它们随机地砍断,使得每一节木棍的长度都不超过50个长度单位。
然后他又想把这些木棍恢复到为裁截前的状态,但忘记了初始时有多少木棒以及木棒的初始长度。
请你设计一个程序,帮助乔治计算木棒的可能最小长度。
每一节木棍的长度都用大于零的整数表示。
思路:
1.木棒的长度一定能被总长度整除
2.木棒的长度一定大于任何一根木棍的长度(枚举的时候可以从木棍最长长度开始)
3.剪支优化:
1.长的木棒选择少(排序)
2.人为定序
3.如果第一根失败了,就失败了
4.如果最后一根失败了,就失败了
5.和失败的木棍一样长的也会失败
代码:
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N=70;
int sticks[N];
bool st[N];
int n;
int sum,length;
bool dfs(int u,int cur,int start)
{
if(u*length==sum) return true;
if(cur==length) return dfs(u+1,0,0);
for(int i=start;i<n;i++)
{
if(st[i]) continue;
int l=sticks[i];
if(cur+l<=length)
{
st[i]=true;
if(dfs(u,cur+l,i+1)) return true;
st[i]=false;
剪枝3 如果是第一个木棒失败,则一定失败
if(!cur) return false;
// 剪枝4 如果是最后一个木棒失败,则一定失败
if(cur+l==length) return false;
// 剪枝2 跳过相同木棒
int j=i;
while(sticks[j]==l) j++;
i=j-1;
}
}
return false;
}
int main()
{
while(cin>>n,n)
{
memset(st,0,sizeof st);
sum=0,length=0;
for(int i=0;i<n;i++)
{
int l;
cin>>l;
sticks[i]=l;
if(l>50) continue;
sum+=l;
length=max(length,l);
}
//剪支,优化搜索顺序性
sort(sticks,sticks+n);
reverse(sticks,sticks+n);
for(int i=0;i<n;i++)
if(sticks[i]>50)
st[i]=true;
while(true)
{
if(sum%length==0 && dfs(0,0,0))
{
cout<<length<<endl;
break;
}
length++;
}
}
return 0;
}