P1450 [HAOI2008]硬币购物
传送~
这是道经典容斥题。我们要求的是
的解的个数。
如果没有
变形一下,得到:
这也是一个完全背包。但因为可以是有一些数满足要求,而另一些不满足,于是就要容斥了。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxs = 1e5;
int c[5], d[5], n, s;
ll f[maxs+10];
int main() {
for (int i = 1; i <= 4; ++i)
scanf("%d", &c[i]);
f[0] = 1;
for (int i = 1; i <= 4; ++i)
for (int j = c[i]; j <= maxs; ++j)
f[j] += f[j-c[i]];
scanf("%d", &n);
while (n--) {
for (int i = 1; i <= 4; ++i)
scanf("%d", &d[i]);
scanf("%d", &s);
ll ans = 0;
for (int i = 1; i < 16; i++) {
int m = s, cnt = 0;
for (int j = 1; j <= 4; j++)
if (i&(1<<(j-1))) m -= (d[j]+1)*c[j], ++cnt;
if (m >= 0) ans += (cnt%2*2-1)*f[m];
}
printf("%lld\n", f[s] - ans);
}
return 0;
}
后记:对于这样所有解减去不合法的技巧,在CSP-S 2019 D2T1也用到了