背包问题主要由三类:
- 01背包
- 完全背包
- 多重背包
1、01背包(使用滚动数组优化)
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int k = 1; k <= t; k++) { int N = sc.nextInt(); // 商品个数 int V = sc.nextInt(); // 总花销 int[] cost = new int[N]; // 单个花销 int[] val = new int[N]; // 单个价值 for (int i = 0; i < N; i++) val[i] = sc.nextInt(); for (int i = 0; i < N; i++) cost[i] = sc.nextInt(); int[] dp = new int[V+1]; // 初始化 for (int i = 0; i <= V; i++) dp[i] = 0; for (int i = 1; i <= N; i++) { ZeroOnePack(dp, V, cost[i-1], val[i-1]); } System.out.printf("%d%n", dp[V]); } } public static void ZeroOnePack(int[] dp, int V, int C, int W) { for (int i = V; i >= C; i--) { dp[i] = Math.max(dp[i], dp[i-C] + W); } } }