是为了什么而流着血

· · 题解

首先扔掉与 0 取 \max 的操作。最后得到的值就是固定的,设为 p,再设过程中的最小值为 q,则取 \max 时最后的 C = p - q。

证明:

观察上图,折线为不取 \max 时 C 的变化情况,当 C < 0 时,在取 \max 的图像中是被抹平的(取 \max 的图没有给出,可以画画看),而很显然,0 下方的图像是不需要减的,这些减有部分需要加回来,比如上图的最低点,需要把 h 平移上去,之后由于没有更低的,所以不会出现负数,不用加,之前的加了之后其实会让 h 减少对应的值,相当于没加,所以只需要加 h = -q 即可,证毕。

所以等价于问 -q \in [L - p, R - p] 的方案数,差分完了就在问 q \ge x 的方案数,使用 dp 可以轻松算出答案(最小值 \ge x 说明所有值 \ge x)。前缀和优化即可。

时间复杂度 \mathcal{O}(n^2)。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
const int N = 5e3 + 10, mod = 998244353;
template<typename T>
void dbg(const T &t) { cout << t << endl; }
template<typename Type, typename... Types>
void dbg(const Type& arg, const Types&... args) {
    cout << arg << ' ';
    dbg(args...);
}
int n, l, r, s1[N], s2[N], f[N][N];
int solve(int x) {
    x += s1[n] - s2[n];
    f[0][0] = 1;
    for (int i = 1; i <= n; i++) for (int j = 0; j <= i; j++) {
        f[i][j] = 0;
        if (s1[i] - s2[j] <= x) {
            f[i][j] = (f[i - 1][j] + (!j ? 0 : f[i][j - 1])) % mod;
        }
    }
    return f[n][n];
}
int main() {
    // freopen("data.in", "r", stdin);
    // freopen("data.out", "w", stdout);
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    cin >> n >> l >> r;
    for (int i = 1, x; i <= n; i++) cin >> x, s1[i] = s1[i - 1] + x;
    for (int i = 1, x; i <= n; i++) cin >> x, s2[i] = s2[i - 1] + x;
    cout << (solve(r) - solve(l - 1) + mod) % mod << '\n';
    return 0;
}