https://www.luogu.org/problemnew/show/P1450
硬币购物一共有4种硬币。面值分别为c1,c2,c3,c4。某人去商店买东西,去了tot次。每次带di枚ci硬币,买si的价值的东西。请问每次有多少种付款方法。
先dp预处理出假设每种硬币有无限个买价值为i的东西的硬币的方案数(完全背包),然后就有两个很思维的东西了。
首先,因为硬币数量有限,根据容斥原理,只要把无限的方案减去第一种硬币超过限制的方案、减去第二种硬币超过限制的方案,减去第三种硬币超过限制的方案、减去第四种硬币超过限制的方案,那么最终就是没有一种硬币超过限制的方案了。但是这样会多减,那就加上两两超过限制的方案,减去三三超过限制的方案,加上四四超过限制的方案,就是最终的结果,这个二进制状压容斥即可。
那么第一种硬币超过限制的方案怎么求呢,那就是假设已经用了(d[1] + 1)个硬币,剩下的硬币任意分配,这样无论如何第一种都是超过限制的,于是第一种硬币超过限制的方案就是dp[s – (d[1] + 1) · c[1]],剩下的同理,那么这题就过了。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 5, mod = 1e9 + 7;
ll c[4], d[4], dp[maxn];
int main()
{
ios::sync_with_stdio(0); cin.tie(0);
int tot;
while (cin >> c[0] >> c[1] >> c[2] >> c[3] >> tot){
dp[0] = 1;
for (int i = 0; i < 4; ++i){
for (int j = 0; j < maxn; ++j){
if (j - c[i] >= 0) dp[j] += dp[j - c[i]];
}
}
while (tot--){
int s;
cin >> d[0] >> d[1] >> d[2] >> d[3] >> s;
ll ans = dp[s];
for (int i = 1; i < (1 << 4); ++i){
int t = i, p = 0, cnt = 0;
ll sum = 0;
while (t){
if (t & 1) ++cnt, sum += (ll)(d[p] + 1) * c[p];
t >>= 1;
++p;
}
if (s - sum < 0) continue;
if (cnt & 1) ans -= dp[s - sum];
else ans += dp[s - sum];
}
cout << ans << '\n';
}
}
return 0;
}