题解 | #采药#01背包模板题,记住就行。
采药
https://www.nowcoder.com/practice/d7c03b114f0541dd8e32ce9987326c16
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); int m = sc.nextInt(); int[] dp = new int[t + 1]; while (m-- != 0) { int weight = sc.nextInt(); int value = sc.nextInt(); for (int i = t; i >= weight; i--) { dp[i] = Math.max(dp[i], dp[i - weight] + value); } } System.out.println(dp[t]); } }