题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2191
思路分析:该问题为多重背包问题;假设状态dp[i][v]表示在前i件物品中选择物品放入大小为v的背包的最大的重量,则可以第i件物品可以选择0~n[i]件,所以可以得出状态方程 dp[i][v] = Max{dp[i-1][v – k * c[i]] + k * w[i]}, 0 <= k <= n[i];
代码如下:
import java.util.*; public class Main { static int MAX_N = 100 + 10; static int[] c = new int[MAX_N]; static int[] w = new int[MAX_N]; static int[] n = new int[MAX_N]; static int[][] dp = new int[MAX_N][MAX_N]; public static int Max(int a, int b) { return a > b ? a : b; } public static void main(String[] args) { int case_times; Scanner in = new Scanner(System.in); case_times = in.nextInt(); while (case_times-- != 0) { int V, M; V = in.nextInt(); M = in.nextInt(); for (int i = 1; i <= M; ++ i) { c[i] = in.nextInt(); w[i] = in.nextInt(); n[i] = in.nextInt(); } for (int i = 0; i < MAX_N; ++ i) for (int j = 0; j < MAX_N; ++ j) dp[i][j] = 0; for (int i = 1; i <= M; ++ i) { for (int v = 0; v <= V; ++ v) { for (int k = 0; k <= n[i]; ++ k) if (v - k * c[i] >= 0) dp[i][v] = Max(dp[i][v], dp[i-1][v - k * c[i]] + k * w[i]); } } System.out.println(dp[M][V]); } } }