0-1背包问题 Java
package beiBao;
public class Knapsack {
public static void KnapSack(int c,int n, int x[],int w[],int v[],int m[][]) {
for(int i = 0;i <= n;i++)
m[i][0] = 0;
for(int j = 0;j <=c ;j++)
m[0][j] = 0;
for(int i = 1;i<=n;i++) {
for(int j = 1;j<=c;j++) {
if(w[i] > j)
m[i][j] = m[i-1][j];
else
m[i][j] = Math.max(m[i-1][j], v[i] + m[i-1][j-w[i]]);
}
}
System.out.println("表f的值");
for(int i = 0;i <= n;i++) {
for(int j = 0;j<=c;j++)
System.out.printf("%-4d",m[i][j]);
System.out.println();
}
int j = c;
for(int i = n;i > 0;i--) {
if(m[i][j] > m[i-1][j] ){
x[i] = 1;
j -= w[i];
}
else
x[i] = 0;
}
System.out.println("表x的值:");
for(int i = 1;i<=n;i++)
System.out.println("x" + i + "=" + x[i] +"\t");
System.out.println();
System.out.printf("总价值为:%d",m[n][c]);
}
public static void main(String[] args) {
int c = 10;
int n = 5;
int x[] = new int[n + 1];
int w[] = new int [] {0,2,2,6,5,4};
int v[] = new int [] {0,6,3,5,4,6};
int m[][] = new int[n+1][c+1];
KnapSack(c, n, x, w, v, m);
}
}
|