您的位置:首页 > 其它

poj-1011-Sticks(深搜、优化)

2013-08-14 12:11 316 查看
[align=center]Sticks[/align]

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 110777 Accepted: 25424
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 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

Source
Central Europe 1995
 
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class Main {

/**
* @param args
*/
static boolean flag=false;
static int edge;
static int number_edge;
static int n;
static Integer[] a;
static boolean[] mark;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
while(true){
n=input.nextInt();
if(n==0)
break;
a=new Integer
;
mark=new boolean
;
int total=0;
for(int i=0;i<n;i++){
a[i]=input.nextInt();
total+=a[i];
}
Arrays.sort(a,new Comparator<Integer>(){

@Override
public int compare(Integer arg0, Integer arg1) {
// TODO Auto-generated method stub
return arg1-arg0;
}

});
//至少两根棍
flag=false;
for(edge=a[0];edge<=total/2;edge++){
if(total%edge==0){
number_edge=total/edge;
dfs(0,0,0);
if(flag==true){
System.out.println(edge);
break;
}

}
}
//一根棍
if(edge>total/2)
System.out.println(total);
}
}//main
private static void dfs(int cur, int curlen, int number) {
// TODO Auto-generated method stub
if(flag==true)
return;
if(number==number_edge-1){
flag=true;
return;
}
if(curlen==edge)
dfs(number+1,0,number+1);
for(int i=cur;i<n;i++){
if(mark[i]==false){
if(curlen+a[i]<=edge){
if(i>0 && a[i]==a[i-1] && mark[i-1]==false)
continue;
mark[i]=true;
dfs(i+1,curlen+a[i],number);
mark[i]=false;
}
if(curlen==0){//等于零,证明是第一支木棒。第一支木棒不行的话剪枝
return;
}
}
}//for
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: