题目:有n(n<=8)个物品需要装入盒子,形状为圆型,且物品必须紧贴盒子底部。情况类似图中所示:
求盒子宽度的最小值。
//forth
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.LinkedList;
import java.util.Scanner;
public class forth {
private final static String fStreamIn = "d.in";
private final static String fStreamOut = "d.out";
private static double width;
public static void main(String[] args) {
try{
//declare global variable for program
Scanner reader = new Scanner(new File(fStreamIn));
Writer writer = new FileWriter(new File(fStreamOut));
try{
int totalNum = reader.nextInt();
LinkedList<Double> datas = new LinkedList<Double>();
for(int i=0;i<totalNum;i++){
datas.add(reader.nextDouble());
}
for(int i=0;i<totalNum;i++){
width+=(datas.get(i));
}
width*=2;
//System.out.println(width);
//按圆半径排序
LinkedList<Double> result = new LinkedList<Double>();
//求值
dfs(datas,result);
System.out.println(String.format("%.3f", width));
//写入文件
writer.write(String.format("%.3f", width));
}catch(Exception ex){
ex.printStackTrace();
}finally{
//close stream
reader.close();
writer.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void dfs(LinkedList<Double> rest,LinkedList<Double> result){
if(rest.size()>0){
for(int i=0;i<rest.size();i++){
LinkedList<Double> next = (LinkedList<Double>)rest.clone();
next.remove(i);
result.add(rest.get(i));
dfs(next,result);
}
}
double sum = 0.0;
for(int i=1;i<result.size();i++){
double r1 = result.get(i);
double r2 = result.get(i-1);
double d1 = (r1+r2)*(r1+r2);
double d2 = (r1-r2)*(r1-r2);
sum += Math.sqrt(d1-d2);
}
sum+=result.get(0);
sum+=result.get(result.size()-1);
if(sum<width){
width = sum;
}
}
}