AcWing 5. 多重背包问题 II (多重背包)

这道题相比上个多重背包,数据范围扩大,直接遍历各个物品的数量会TLE,这个地方用到一个巧妙地优化方法:二进制。

例如1,2,4,8,16,…
16以内的正整数能用20 21 22 23 凑出来,所以把物品打包来处理,不会遗漏任何数字。

题目

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

class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pw = new PrintWriter(System.out);
    static int N = 2010;
    static int n, m;
    static int f[] = new int[N];
    static ArrayList<Good> al = new ArrayList<>();

    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 = 0; i < n; i++) {
            s = br.readLine().split(" ");
            int w = Integer.parseInt(s[0]);
            int v = Integer.parseInt(s[1]);
            int c = Integer.parseInt(s[2]);

            for (int k = 1; k <= c; k *= 2) {
                c -= k;
                al.add(new Good(k * w, k * v));
            }

            if (c > 0) al.add(new Good(c * w, c * v));
        }

        for (Good g : al) {
            for (int i = m; i >= 0; i--)
                if (i >= g.getW())
                    f[i] = Math.max(f[i], f[i - g.getW()] + g.getV());
        }
        pw.println(f[m]);
        pw.flush();
        pw.close();
        br.close();
    }
}

class Good {
    int w;
    int v;

    public Good(int w, int v) {
        this.w = w;
        this.v = v;
    }

    public int getW() {
        return w;
    }

    public void setW(int w) {
        this.w = w;
    }

    public int getV() {
        return v;
    }

    public void setV(int v) {
        this.v = v;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值