這兩天看高程中的演算法,把其中的遞迴揹包問題用java執行了。特請高手們指點!

seemee發表於2005-04-04
/*
* Created on Apr 2, 2005
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package com.kevin.datastru;

/**
* @author seemee
*
* To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
/*import java.io.BufferedReader;
import java.io.InputStreamReader;*/
import java.io.IOException;

public class CarryBag {
double limitW, totV, maxv;
int option[] = new int[100], cop[] = new int[100];
Struct a[]= new Struct[100];
int n;

public void find(int i, double tw, double tv){
int k;

if ( tw + a.weight <= limitW){
cop=1;
if(i<n-1){
find(i+1, tw+a.weight, tv);
}
else {
for(k=0;k<n;k++){
option[k] = cop[k];
}
maxv = tv;
}
cop = 0;
}

if (tv - a.value > maxv) {
if (i < n-1) {
find(i+1, tw, tv - a.value);
}
else {
for (k = 0; k<n; k++){
option[k] = cop[k];
}
maxv = tv - a.value;
}
}
}

public static void main(String[] args) throws IOException{
int k;

CarryBag cBag = new CarryBag();
cBag.a[0] = cBag.new Struct(5.0, 4.0);
cBag.a[1] = cBag.new Struct (3.0, 4.0);
cBag.a[2] = cBag.new Struct (2.0, 3.0);
cBag.a[3] = cBag.new Struct (1.0, 1.0);

cBag.limitW = 7.0;
cBag.maxv = 0.0;
cBag.totV = 12.0;

cBag.n = 4;

for (k = 0; k < cBag.n ; k++) {
cBag.cop[k] = 0;
}

cBag.find(0, 0.0, cBag.totV);

for(k = 0; k < cBag.n ; k++){
if(cBag.option[k] != 0) {
System.out.println(k);
}
}
System.out.println(cBag.maxv);
}

class Struct{
double weight;
double value;
Struct (double weight, double value){
this.weight = weight;
this.value = value;
}
}

}



以上程式碼複製、貼上即可執行!

相關文章