题解:P1450 [HAOI2008] 硬币购物
superLouis · · 题解
题解:P1450 [HAOI2008] 硬币购物
我翻遍了所有的题解,竟没有一个人写单调队列优化 DP 的思路,于是过来写一篇。
1. 解题思路
对于每次购买,其实就是有
我们不难发现,这不就是一个裸的求多重背包方案数的题吗?我看很多的题解也下了这一点。但很多题解说多重背包的时间复杂度是
想到二进制拆分优化多重背包,但是二进制拆分优化多重背包的方法只适用于求最优解和可行性问题,不能用来求方案数。所以可以用⼀种单调队列的优化方法,能将复杂度优化到
现在说一下单调队列优化多重背包的思路。先跳出这个题,考虑最标准的多重背包方案数问题。
有
考虑最朴素的转移方程:
其中
现在,我们将所有重量
其中
对于每个余数
- 窗口范围:
t\in [x-c_i,x] - 需要快速计算:
\sum_{t=L}^{R} g_{r+t\cdot w}
对于实现,用一个双端队列存储窗口内所有元素值。每次右移时,队尾加入新元素,队头移除过期元素。维护一个变量 sum,累加或减去进出队列的元素。
void optimize(int v, int w, int c) {
memcpy(g, f, sizeof(f));
for (int r = 0; r < w; r++) {
int head = 0, tail = -1, sum = 0;
for (int x = 0; r + x * w <= v; x++) {
int pos = r + x * w;
sum += g[pos];
q[++tail] = x;
while (head <= tail && q[head] < x - c) {
int oldpos = r + q[head] * w;
sum -= g[oldpos];
head++;
}
f[pos] = sum;
}
}
}
2. 代码实现
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int maxn = 1e5 + 10;
int c[4], d[4], n, s, f[maxn], g[maxn], dq[maxn << 1];
void func(int m, int w, int cnt) {
memcpy(g, f, (m + 1) * sizeof(int));
for (int r = 0; r < w; r++) {
int head = 1, tail = 0, sum = 0;
for (int x = 0; r + x * w <= m; x++) {
int pos = r + x * w;
sum += g[pos];
dq[++tail] = x;
while (head <= tail && dq[head] < x - cnt) {
int oldpos = r + dq[head] * w;
sum -= g[oldpos];
head++;
}
f[pos] = sum;
}
}
}
signed main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> c[0] >> c[1] >> c[2] >> c[3] >> n;
while (n--) {
cin >> d[0] >> d[1] >> d[2] >> d[3] >> s;
memset(f, 0, sizeof(f));
f[0] = 1;
for (int i = 0; i < 4; i++) func(s, c[i], d[i]);
cout << f[s] << "\n";
}
return 0;
}
大约要跑
测评记录