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

可以想到这是一个背包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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值