[BZOJ1042][HAOI2008]硬币购物(背包+容斥)

本文介绍了一种结合背包动态规划与容斥原理解决特定问题的方法。通过限制硬币数量来优化传统背包DP算法,实现了在常数时间内解决询问的目标。文章提供了完整的代码实现,并解释了如何利用容斥原理来减少超出限制的方案数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以想到这是一个背包DP,但是由于数据规模的原因,不能每次都进行一次DP。
于是从「硬币数量只有4」这个条件上入手。由容斥原理得到:
总方案数=不限制的方案数1种硬币超过限制的方案数+2种硬币超过限制的方案数3种硬币超过限制的方案数+4种硬币全部超过限制的方案数
于是可以跑一遍完全背包DP之后,在常数(16)时间内解决一组询问。

#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
inline int read() {
    int res = 0; bool bo = 0; char c;
    while (((c = getchar()) < '0' || c > '9') && c != '-');
    if (c == '-') bo = 1; else res = c - 48;
    while ((c = getchar()) >= '0' && c <= '9')
        res = (res << 3) + (res << 1) + (c - 48);
    return bo ? ~res + 1 : res;
}
typedef long long ll;
const int MaxN = 1e5, N = MaxN + 5;
int T, c[6], d[6], S; ll ans, f[N];
void dfs(int dep, int cnt, int s_now) {
    if (dep == 5) {
        if (cnt & 1) ans -= f[s_now];
        else ans += f[s_now];
        return;
    }
    dfs(dep + 1, cnt, s_now);
    if (s_now >= 1ll * c[dep] * (d[dep] + 1))
        dfs(dep + 1, cnt + 1, s_now - c[dep] * (d[dep] + 1));
}
int main() {
    int i, j; cin >> c[1] >> c[2] >> c[3] >> c[4] >> T; f[0] = 1;
    for (i = 1; i <= 4; i++) for (j = c[i]; j <= MaxN; j++)
        f[j] += f[j - c[i]];
    while (T--) {
        for (i = 1; i <= 4; i++) d[i] = read(); S = read();
        ans = 0; dfs(1, 0, S); printf("%lld\n", ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值