以下内容来自我的线段树学习笔记。
链接。
把这个集合用权值线段树维护,发现合并是困难的,于是尝试化式子。
观察到
令 为序列 的和, 为序列 的长度, 为序列 的权值。
那么有 。
照着这个维护即可,注意动态开点。
代码
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 200010, MaxN = 1e9, mod = 998244353;
namespace Segment_Tree
{
struct Info { int val, len, sum; };
inline Info push_up (const Info &l, const Info &r)
{
Info T;
T.sum = (l.sum + r.sum) % mod; T.len = l.len + r.len;
T.val = (l.val + r.val + l.len * r.sum) % mod;
return T;
}
#define ls (sgt[u].l)
#define rs (sgt[u].r)
int idx = 0;
struct Sgt { int l, r; Info w; } sgt[N * 40];
inline void push_up (const int &u) { sgt[u].w = push_up(sgt[ls].w, sgt[rs].w); }
inline void update (int &u, const int &ql, const int &qr, const int &x, const int &k)
{
if (u == 0) u = ++idx;
if (ql == qr)
{
if (k == 1) sgt[u].w.len++,
(sgt[u].w.sum += x) %= mod,
sgt[u].w.val = sgt[u].w.len * (sgt[u].w.len + 1) / 2 % mod * x % mod;
else sgt[u].w.len--,
(((sgt[u].w.sum -= x) %= mod) += mod) % mod,
sgt[u].w.val = sgt[u].w.len * (sgt[u].w.len + 1) / 2 % mod * x % mod;
return ;
}
int mid = ql + qr >> 1;
if (x <= mid) update(ls, ql, mid, x, k);
else update(rs, mid + 1, qr, x, k);
push_up(u);
}
inline Info query (const int &u, const int &ql, const int &qr, const int &l, const int &r)
{
if (u == 0) return (Info) {0, 0, 0};
if (l <= ql && qr <= r) return sgt[u].w;
int mid = ql + qr >> 1;
if (qr <= mid) return query(ls, ql, mid, l, r);
if (ql > mid) return query(rs, mid + 1, qr, l, r);
return push_up(query(ls, ql, mid, l, r), query(rs, mid + 1, qr, l, r));
}
}
using namespace Segment_Tree;
int n, q, rt;
signed main ()
{
// freopen("test.in", "r", stdin);
scanf("%lld %lld", &n, &q);
for (int i = 1; i <= n; i++)
{
int x; scanf("%lld", &x);
update(rt, 0, MaxN, x, 1);
}
while (q--)
{
int opt;
scanf("%lld", &opt);
if (opt <= 2)
{
int x; scanf("%lld", &x);
update(rt, 0, MaxN, x, 3 - opt * 2);
}
else printf("%lld\n", query(rt, 0, MaxN, 0, MaxN).val % mod);
}
return 0;
}