题解 | #【模板】完全背包#
【模板】完全背包
https://www.nowcoder.com/practice/237ae40ea1e84d8980c1d5666d1c53bc
import java.util.Arrays; import java.util.Scanner; public class Main { public static int solution(int V, int[][] wuping) { int[] dp = new int[V + 1]; for (int i = 1; i <= V; i++) { for (int j = 0; j < wuping.length; j++) { int[] item = wuping[j]; if (i >= item[0]) { dp[i] = Math.max(dp[i], dp[i - item[0]] + item[1]); } } } return dp[V]; } public static int solution2(int V, int[][] wuping) { int[] dp = new int[V + 1]; Arrays.fill(dp, -1); dp[0] = 0; for (int i = 1; i <= V; i++) { for (int j = 0; j < wuping.length; j++) { int[] item = wuping[j]; if (i >= item[0] && dp[i - item[0]] >= 0) { dp[i] = Math.max(dp[i], dp[i - item[0]] + item[1]); } } } return dp[V] < 0 ? 0 : dp[V]; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int V = in.nextInt(); int[][] wuping = new int[n][]; for (int i = 0; i < wuping.length; i++) { int tiji = in.nextInt(); int value = in.nextInt(); wuping[i] = new int[] {tiji, value}; } int res = solution(V, wuping); System.out.println(res); System.out.println(solution2(V, wuping)); } }