回溯法 | 子集树:装载问题

学习链接:回溯法:最优装载问题回溯法最优装载问题(java)


 

输入:

int[]w={21,10,5};
        Load_Cargo problem=new Load_Cargo(w,34);

输出:

最大装载量:31
应装入的货物:1 2 

java代码:

 1 class Load_Cargo{//装载问题
 2     int[] w;//各货物的重量
 3     int wMax;//最大载重量
 4     int nowWei=0;//当前载重量
 5     int bestWei=0;//最优重量    
 6     
 7     int restCargo=0;//剩余货物重量
 8     int cargo_len=0;//货物数目
 9     
10     int []x;//当前解向量    
11     int []bestX;//最优解
12 
13     Load_Cargo(int[] w,int wMax){
14         this.w=w;
15         this.wMax=wMax;
16         cargo_len=w.length;
17         x=new int[cargo_len];
18         bestX=new int[cargo_len];
19         int i;
20         for(i=0;i<cargo_len;i++){
21             restCargo+=w[i];
22         }
23     }
24     void solve(){
25         BackTrace(0);
26         System.out.println("最大装载量:"+bestWei);
27         System.out.print("应装入的货物:");
28         for(int i=0;i<cargo_len;i++){
29             if(bestX[i]==1){
30                 System.out.print((i+1)+" ");
31             }
32         }
33         System.out.println();
34     }
35     void BackTrace(int t){
36         if(t<cargo_len){//如果没有抵达叶子节点
37             restCargo-=w[t];//剩余货物 减去 当前货物重量
38             //遍历左子树
39             if(nowWei+w[t]<=wMax){//如果当前货物能放入
40                 nowWei+=w[t];
41                 x[t]=1;
42                 BackTrace(t+1);
43                 nowWei-=w[t];
44             }
45             //遍历右子树
46             if(nowWei+restCargo>bestWei){//如果当前重量 加上 剩余货物 比最优解重
47                 x[t]=0;
48                 BackTrace(t+1);
49             }
50             restCargo+=w[t];//恢复 剩余货物重量
51         }else{//叶子节点,回溯完毕
52             int a;
53             a=0;
54             if(nowWei>bestWei){//当前重量大于剩余重量
55                 //更新最优解向量
56                 bestX=x.clone();
57                 bestWei=nowWei;
58             }
59         }
60     }
61     
62 }

 

posted @ 2017-10-17 13:55  TQCAI  阅读(2511)  评论(0编辑  收藏  举报