背包问题

背包问题主要由三类:

  1. 01背包
  2. 完全背包
  3. 多重背包

 

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);
        }
    }
}

 

背包问题

上一篇:如何保证接口的幂等性?


下一篇:Codeforces Round #739 (Div. 3) F. Nearest Beautiful Number(思维、贪心)