好的,我遇到了背包问题的Memory Function实现问题。我的实现如果在Java中给我错误的答案但在C ++中相同的实现给了我正确的答案。
import java.io.*;
import java.util.*;
public class KnapsackMF {
public static void main(String args[]){
int wt;
int vl;
long start, end, runTime;
Scanner input = new Scanner(System.in);
int n, W;
System.out.println("Please enter the number of items: ");
n = input.nextInt();
System.out.println("Please enter the capacity of the knapsack: ");
W = input.nextInt();
int[][] V = new int[n+1][W+1];
int[] Wt = new int[n];
int[] Vl = new int[n];
for(int i = 0; i < n; i++){
System.out.println("Enter the weight and the value of item " + i + ": ");
wt = input.nextInt();
vl = input.nextInt();
Wt[i] = wt;
Vl[i] = vl;
}
for(int i = 0; i <= n; i++ ){
for(int j = 0; j <= W; j++){
if(j == 0 || i == 0){
V[i][j] = 0;
}
else{
V[i][j] = -1;
}
}
}
/*
for(int i= 0; i <= n; i++){
for(int j = 0; j <= W; j++){
System.out.print(V[i][j] + " ");
}
System.out.println();
}
*/
start = System.nanoTime();
System.out.println("The highest value is: " + MFKnapsack(n, W, V, Vl, Wt));
end = System.nanoTime();
runTime = (end - start);
System.out.println("Nanoseconds: " + runTime);
for(int i= 0; i <= n; i++){
for(int j = 0; j <= W; j++){
System.out.print(V[i][j] + " ");
}
System.out.println();
}
//system("PAUSE");
}
public static int MFKnapsack(int i, int j, int[][] V, int[] Vl, int[] Wt){
int value = 0;
if(V[i][j] < 0){
if(j < Wt[i-1]){
value = MFKnapsack(i-1, j, V, Vl, Wt);
}
else{
value = Math.max(MFKnapsack(i-1, j, V, Vl, Wt), Vl[i-1] + MFKnapsack(i-1, j-Wt[i-1], V, Vl, Wt));
}
}
V[i][j] = value;
return V[i][j];
}
}
我使用的例子不在我的书中,输入应该是:
4
5
2 12
1 10
3 20
2 15
对此的答案应该是37,但是有些情况正在发生,我没有看到,它给了我35个。