DFS+剪枝
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
题意:一组等长的木棒,将它们随机地裁断,使得每一节木棒的长度都不超过50个长度单位。然后把这些木棒恢复到为裁截前的状态,但忘记了木棒的初始长度。设计一个程序,计算木棒的可能最小长度。每一节木棒的长度都用大于零的整数表示。(题意不是太好概括,就直接翻译一下)
一开始不出所料的TLE了,后来才意识到要设计剪枝。
第一次设计剪枝有点懵逼,没有想到其实很显然也是最关键的那步,卡了整整一天,不得已看了看别人的想法。
其实就是排除掉重复的,这样就不会TLE。
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstring>
#define Maxn 100
using namespace std;
bool ending=false;
int n,sti[Maxn],vis[Maxn]={0},sum,m,len=-1;
bool compare(int a,int b){
return a>b;
}
void dfs(int prev_n,int pres_l,int idn){
if(ending==true) return;
if(pres_l==len){
if(prev_n==n) ending=true;
else dfs(prev_n,0,0);
return;
}
if(pres_l==0){
while(vis[idn]==1) idn++;
vis[idn]=1;
dfs(prev_n+1,sti[idn],idn+1);
vis[idn]=0;
}
else{
for(int i=idn;i<n;i++){
if(vis[i]==0&&pres_l+sti[i]<=len){
if(vis[i-1]==0&&sti[i]==sti[i-1]) continue;
vis[i]=1;
dfs(prev_n+1,pres_l+sti[i],i+1);
vis[i]=0;
}
}
}
}
int main()
{
while(cin>>n&&n){
sum=m=0; ending=false;
for(int i=0;i<n;i++){
cin>>sti[i];
sum+=sti[i]; m=max(sti[i],m);
}
sort(sti,sti+n,compare);
for(len=m;len<sum;len++){
if(sum%len!=0) continue;
else{
memset(vis,0,sizeof(vis));
dfs(0,0,0);
if(ending==true) break;
}
}
cout<<len<<endl;
}
return 0;
}
感觉自己会因为嫌麻烦,设计剪枝的时候很容易烦躁……得多练练。