简单的动态规划
输入一个n,表示有n道题,接下来的n个表示每道题的分数,再接下来的n个表示每道题的花费时间,最后输入考试总时间长度。(每道题都能做上)
输出:该场考试能获得的最高分数
public class Score {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] score = new int[n];
int[] time = new int[n];
for(int i=0; i<n; i++) {
score[i] = sc.nextInt();
}
for(int i=0; i<n; i++) {
time[i] = sc.nextInt();
}
int total = sc.nextInt();
int[][] dp = new int[n+1][total+1];
int[][] path = new int[n+1][total+1];
//初始化第一列和第一行
for(int i=0;i<dp.length;i++){
dp[i][0] = 0;
}
for(int i=0;i<dp[0].length;i++){
dp[0][i] = 0;
}
for(int i=1; i<dp.length; i++) {
for(int j=1; j<dp[0].length;j++) {
if(time[i-1] > j) {
dp[i][j] = dp[i-1][j];
}
else {
if(dp[i-1][j]<dp[i-1][j-time[i-1]]+score[i-1]){
dp[i][j] = dp[i-1][j-time[i-1]]+score[i-1];
path[i][j] = 1;
}else{
dp[i][j] = dp[i-1][j];
}
}
}
}
int i=dp.length-1;
int j=dp[0].length-1;
int sum = 0;
while(i>0&&j>0){
if(path[i][j] == 1){
System.out.print("第"+i+"个物品装入 ");
sum += score[i-1];
j -= time[i-1];
}
i--;
}
System.out.println(sum);
}
}