题解:CF2053I2 Affectionate Arrays (Hard Version)
与其他两篇题解不同的做法。
注意到
所以我们证明了,序列
设
考虑对这个限制 dp,容易发现,对于
所以最终
设
加入
分别考虑这两步转移。对于第一步转移,相当于是将前/后
对于第二步转移,设
注意到上述所有操作都是均摊
注意特判
不多测版本代码:
#include<bits/stdc++.h>
#include<bits/extc++.h>
#define rep(i,l,r) for (int i = l; i <= r; i ++)
#define rrp(i,l,r) for (int i = l; i >= r; i --)
using namespace std;
typedef long long LL;
const int N = 3e6 + 5, mod = 998244353;
inline void inc(int &x, int y) { unsigned t = x + y; x = min(t, t - mod); }
int n;
LL a[N], sum;
struct node { LL l; int x, c; } qq[N << 1];
int hd, tl, val[N], tag[N];
LL cnt[N];
bool vis[N];
vector<int> Q;
int gettop() {
sort(Q.begin(), Q.end(), greater<int>());
int x = Q.back();
for (; cnt[x] == 0; )
Q.pop_back(), vis[x] = 0, x = Q.back();
return x;
}
void add(node u) {
if (!vis[u.x]) Q.push_back(u.x), vis[u.x] = 1;
cnt[u.x] += u.l, inc(val[u.x], u.l % mod * (u.c + tag[u.x]) % mod);
}
void del(node u) {
cnt[u.x] -= u.l, inc(val[u.x], mod - u.l % mod * (u.c + tag[u.x]) % mod);
}
void addtag(int x, int v) {
assert(v < mod);
inc(tag[x], v), val[x] = (val[x] + cnt[x] % mod * v) % mod;
}
signed main() {
cin.tie(0)->ios::sync_with_stdio(0);
cin >> n;
rep (i, 1, n) cin >> a[i], sum += a[i];
if (sum == 0) { cout << "1\n"; return 0; }
hd = n, tl = n - 1;
qq[++ tl] = {1, 0, 1}, add(qq[tl]);
qq[++ tl] = {sum, 1, 1}, add(qq[tl]);
rep (i, 1, n) {
if (a[i] > 0) {
node cur = {0, 0, 0}; LL nd = a[i];
while (nd) {
cur = qq[tl], del(cur);
LL w = min(cur.l, nd);
cur.l -= w, nd -= w, -- tl;
}
if (cur.l) qq[++ tl] = cur, add(cur);
int v = gettop();
qq[-- hd] = {a[i], v + 1, mod - tag[v + 1]}, add(qq[hd]);
addtag(v + 1, val[v]);
} else if (a[i] < 0) {
node cur; LL nd = -a[i];
while (nd) {
cur = qq[hd], del(cur);
LL w = min(cur.l, nd);
cur.l -= w, nd -= w, ++ hd;
}
if (cur.l) qq[-- hd] = cur, add(cur);
int v = gettop();
qq[++ tl] = {-a[i], v + 1, mod - tag[v + 1]}, add(qq[tl]);
addtag(v + 1, val[v]);
} else { // a[i] == 0
int v = gettop(); addtag(v + 1, val[v]);
}
}
cout << (qq[tl].c + tag[qq[tl].x] % mod) % mod << '\n';
return 0;
}