AAL Contest 001: Let’s use Treap!
发现这个动态插入删除平衡树很能做,首先假设我们已经知道两个子树答案,然后这个加权和发现合并的时候,右子树的每个元素系数相当于整体平移了左子树和根的总大小,于是乘上一个这个系数即可。节点维护子树加权和,子树大小。
Code
// Author: albertting
// Time: 2026/10/12 15:20:04
#include <bits/stdc++.h>
#define __Made return
#define in 0
#define China__ ;
#define ll long long
#define ld long double
#define lll __int128
#define pb push_back
#define uset unordered_set
#define umap unordered_map
using namespace std;
constexpr ll P = 998244353;
struct FHQTreap {
using T = int;
struct Node {
int l, r;
T val;
unsigned pri;
int sz;
ll sum;
ll wsum;
};
int n;
vector<Node> tr;
int tot;
int root;
static unsigned rng() {
static uint64_t x = chrono::steady_clock::now().time_since_epoch().count();
x += 0x9e3779b97f4a7c15ULL;
uint64_t z = x;
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
return (unsigned)(z ^ (z >> 31));
}
public:
FHQTreap(int _n = 0) { init(_n); }
void init(int _n) {
n = _n;
tot = 0;
root = 0;
tr.assign(n + 10, Node{0, 0, T(0), 0, 0, 0, 0});
}
void insert(T x) {
int a, b;
split(root, x, a, b);
root = merge(merge(a, newNode(x)), b);
}
void erase(T x) {
int a, b, c;
split(root, x, a, b);
split(a, x - 1, a, c);
c = merge(tr[c].l, tr[c].r);
root = merge(merge(a, c), b);
}
ll queryWeightedSum() const {
return tr[root].wsum;
}
private:
int newNode(T x) {
tr[++tot] = {0, 0, x, rng(), 1, (ll)x % P, (ll)x % P};
return tot;
}
void pushUp(int u) {
int l = tr[u].l, r = tr[u].r;
tr[u].sz = tr[l].sz + tr[r].sz + 1;
tr[u].sum = (tr[l].sum + tr[r].sum + tr[u].val) % P;
tr[u].wsum = (tr[l].wsum + tr[r].wsum
+ (ll)(tr[l].sz + 1) % P * ((tr[r].sum + tr[u].val) % P) % P) % P;
}
void split(int u, T key, int &l, int &r) {
if(!u) {
l = r = 0;
return;
}
if(tr[u].val <= key) {
l = u;
split(tr[u].r, key, tr[u].r, r);
} else {
r = u;
split(tr[u].l, key, l, tr[u].l);
}
pushUp(u);
}
int merge(int l, int r) {
if(!l || !r) return l + r;
if(tr[l].pri > tr[r].pri) {
tr[l].r = merge(tr[l].r, r);
pushUp(l);
return l;
} else {
tr[r].l = merge(l, tr[r].l);
pushUp(r);
return r;
}
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0), clog.tie(0);
int n, q;
cin >> n >> q;
FHQTreap tr(n + q + 5);
for(int i = 1; i <= n; i++) {
int x;
cin >> x;
tr.insert(x);
}
while(q--) {
int op;
cin >> op;
if(op == 1) {
int x;
cin >> x;
tr.insert(x);
} else if(op == 2) {
int x;
cin >> x;
tr.erase(x);
} else {
cout << tr.queryWeightedSum() % P << '\n';
}
}
__Made in China__
}