回溯法 典型题目
Sticks
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 2164 Accepted Submission(s): 493
Problem 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 file 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
Source
Recommend
lcy
package D0808;
import java.io.*;
public class HDU1455 {
static int n,len,m,sum;
static boolean flag;
static int[] sticks;
static boolean[]used;
public static void main(String[] args) throws IOException {
StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
while(st.nextToken()!=StreamTokenizer.TT_EOF){
n = (int)st.nval;
if(n==0)break;
flag = false;
sticks = new int[n];
used = new boolean[n];
sum = 0;
for(int i = 0;i<n;i++){
st.nextToken();
sticks[i] = (int)st.nval;
sum+=sticks[i];//所有棍子长度之和
}
//将棍子从大到小排列
for(int i = 0;i<n;i++)
for(int j = i+1;j<n;j++)
if(sticks[i]<sticks[j]){
sticks[i] = sticks[i]^sticks[j];
sticks[j] = sticks[i]^sticks[j];
sticks[i] = sticks[i]^sticks[j];
}
//最小的长度肯定大于等于这堆棒子中的最大长度小于这堆棒子之和
for(len = sticks[0];len<=sum;len++){
if(sum%len == 0){//重要的减剪枝,len一定要是sum的因数
m = sum/len;//切之前有m根棍子
dfs(0,0,0);
if(flag)break;
}
}
System.out.println(len);
}
}
/*
* @pos:记录当前sticks数组中比较到了哪根棍子了
* @current:记录当前搜索的棍子的长度之和
* @cnt:已经找到的最小棍子长度的数量
* */
public static void dfs(int pos,int current,int cnt){
if(cnt == m)flag = true;//如果以当前的长度能正好匹配完所有的木棒的时候则返回,完成任务,当前长度就是要匹配的最小长度
else if(current == len)//如果curren==len表示 当前完成一次匹配,找到的棍子数目加1.
dfs(0,0,cnt+1);
else{
int pre = -1;
for(int i = pos;i<n;i++){
//如果当前木棒没有被搜索过,并且不等于前面已经搜索过的木棒的长度并且current+当前要
//搜索的木棒长度小于等于假设的最小木棒的长度,就进行匹配。这个剪枝很重要
if(!used[i] && sticks[i]!=pre && current + sticks[i] <= len){
used[i] = true;
pre = sticks[i];
dfs(pos+1, current+sticks[i], cnt);
//如果当前匹配不成功,则将标志恢复
used[i] = false;
//如果只剩下一根木棒获知搜索成功,返回,不能放到函数最后,会超时(算是一个剪枝吧)
if(pos ==0 || flag)return;
}
}
}
}
}