package dynamicprogramming;
import java.util.LinkedList;
class LocationItem {
public String location;
public int score;
public int time;
LocationItem(String location, int score, int time) {
this.location = location;
this.score = score;
this.time = time;
}
}
public class Journey {
public static LinkedList<LocationItem> journey(int days, LocationItem[] items) {
int row = days + 1;
int col = items.length + 1;
LinkedList<LocationItem> chooseLocation = new LinkedList<>();
int[][] cell = new int[row][col];
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
cell[i][j] = 0;
}
}
for(int i = 1; i < row; i++) {
for(int j = 1; j < col; j++) {
if (items[i - 1].time <= j) {
cell[i][j] = Math.max((items[i-1].score + cell[i-1][j-items[i-1].time]), cell[i-1][j]);
} else {
cell[i][j] = cell[i-1][j];
}
}
}
System.out.println(cell);
int i = row - 1;
int j = col - 1;
while (i > 0 && j > 0) {
if (cell[i][j] != cell[i - 1][j]) {
chooseLocation.addFirst(items[i - 1]);
j = j - items[i - 1].time;
i = i - 1;
} else {
i = i - 1;
}
}
return chooseLocation;
}
public static void test() {
LocationItem[] items = {
new LocationItem("故宫", 7, 1),
new LocationItem("颐和园", 8, 2),
new LocationItem("长城", 9, 3),
new LocationItem("天坛", 6, 1)
};
LinkedList<LocationItem> chooseLocation = journey(4, items);
int maxValue = 0;
System.out.println("旅程如下:");
for (int i = 0; i < chooseLocation.size(); ++i) {
maxValue += chooseLocation.get(i).score;
System.out.println(chooseLocation.get(i).location + " 评分:"+ chooseLocation.get(i).score);
}
System.out.println("总评分:" + maxValue);
}
public static void main(String[] args) {
test();
}
}