算法装载问题
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
算法设计与分析实验报告-
1.实验要求:
将n个集装箱装上载重量为c1和c2的轮船,其中集装箱总重量 3.程序代码 package javaapplication1; import java.io.*; public class Main { static int n; static int []w; static int c1,c2; static int cw; static int bestw; static int r; static int []x; static int []bestx; public static int maxloading(int[]ww,int cc,int[]xx){ w=ww; c1=cc; bestw=0; cw=0; x=new int[n+1]; bestx=xx; r=0; for(int i=1;i<=n;i++) r+=w[i]; backtrack(1); return bestw; } private static void backtrack(int i){ if(i>n){ if(cw>bestw){ for(int j=1;j<=n;j++) bestx[j]=x[j]; bestw=cw; } return; } r-=w[i]; if(cw+w[i]<=c1){ x[i]=1; cw+=w[i]; backtrack(i+1); cw-=w[i]; } if(cw+r>bestw){ x[i]=0; backtrack(i+1); } r+=w[i]; } public static void main(String[] args) throws IOException { BufferedReader read =new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); String a=new String(); a=read.readLine(); n=Integer.parseInt(a); System.out.println("集装箱个数: "+n); x=new int[n+1]; String[]b=new String[n]; a=read.readLine(); System.out.println("集装箱重量: "+a); b=a.split(","); w=new int[n+1]; for(int i=1;i<=n;i++){ w[i]=Integer.parseInt(b[i-1]); } a=read.readLine(); c1=Integer.parseInt(a); a=read.readLine(); c2=Integer.parseInt(a); System.out.println("轮船载重量: "+c1+","+c2); int result= maxloading(w,c1,x); int max,temp; for(int i=1;i<3;i++){ for(int j=2;j<3;j++){ if(w[i]>w[j]){ temp=w[i]; w[i]=w[j]; w[j]=temp; } } } if((w[3]>c1)&&(w[3]>c2)){ System.out.println("都不可装"); } else{System.out.println("轮船1装载的集装箱:"); for (int u=1;u if(bestx[u]==1) System.out.println(u+" "); if(r>(result+c2)) System.out.println("轮船1可装:"+result+" "+"轮船2装不完."); else{ System.out.println("轮船2装载的集装箱:"); for (int u=1;u if(bestx[u]==0) System.out.println(u+" "); System.out.println("最优装载--轮船1:"+result+" "+"轮船2:"+(r-result)); } } PrintWriter print=new PrintWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))); if((w[3]>c1)&&(w[3]>c2)){ print.println("都不可装。"); } else{ print.println("轮船1装载的集装箱:"); for (int u=1;u if(bestx[u]==1) print.println(u+" "); if(r>(result+c2)) print.println("轮船1可装:"+result+" "+"轮船2装不完。"); else{ print.println("轮船2装载的集装箱:"); for (int u=1;u if(bestx[u]==0) print.println(u+" "); print.println("最优装载--轮船1:"+result+" "+"轮船2:"+(r-result));