题目要求
分析
荐读:大神博文 -> 《聊聊动态规划与记忆化搜索》
这题就是一个标准的DP水题,对于不会DP的萌新,太难了!对于整天搞DP的算法大佬,水爆了!
荐读:超神著作 -> 《背包九讲》,大噶也可以去Github上下载这个《背包九讲》!学DP必读!
这个题可以压缩成一维得到状态转移方程: ,使用这个你就能解出来了。
如果你真的没做过DP,我建议你读读《背包九讲》的第一Part,然后可以(如果您不嫌弃的话)读读我的题解代码,嗯,就这样。真的我觉得依自己现在的水平,讲也讲不过大神的《背包九讲》。比不过你,我就推荐你,哈哈!
AC代码(Java语言描述)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int time = scanner.nextInt(), num = scanner.nextInt();
int[] f = new int[time+1];
int[] cost = new int[num], value = new int[num];
for (int i = 0; i < num; i++) {
cost[i] = scanner.nextInt();
value[i] = scanner.nextInt();
}
scanner.close();
for (int i = 0; i < num; i++) {
for (int j = time; j >= 0; j--) {
if (j >= cost[i]) {
f[j] = Math.max(f[j], f[j-cost[i]]+value[i]);
}
}
}
System.out.println(f[time]);
}
}