天天看点

AcWing 9. 分组背包问题(背包)

分组背包,每组只能拿一个。

题目

大同小异,在每个组中判断,f[i][j]表示前i组,总体积不大于j的最大数。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pw = new PrintWriter(System.out);
    static int N = 110;
    static int v[][] = new int[N][N], w[][] = new int[N][N], f[] = new int[N], g[] = new int[N];
    static int n, m;

    public static void main(String[] args) throws IOException {
        String[] s = br.readLine().split(" ");
        n = Integer.parseInt(s[0]);
        m = Integer.parseInt(s[1]);
        for (int i = 1; i <= n; i++) {
            s = br.readLine().split(" ");
            g[i] = Integer.parseInt(s[0]);
            for (int j = 0; j < g[i]; j++) {
                s = br.readLine().split(" ");
                w[i][j] = Integer.parseInt(s[0]);
                v[i][j] = Integer.parseInt(s[1]);
            }
        }

        for (int i = 1; i <= n; i++)
            for (int j = m; j >= 0; j--)
                for (int k = 0; k < g[i]; k++)
                    if (j >= w[i][k])
                        f[j] = Math.max(f[j], f[j - w[i][k]] + v[i][k]);

        pw.println(f[m]);
        pw.flush();
        pw.close();
        br.close();
    }
}