题解:AT_aalc001_k 多重集合
AAL Contest 001: Let's use President 01-Trie!
发现本题要求的操作前两个直接在 01-Trie 上打 tag 就好。你正常地按二进制从高位到低位建 Trie,左子树全部小于右子树,中序遍历就是升序。考虑每个节点维护子树大小 cnt、子树元素和 sum、子树排序后的加权和 ans。
假设已知左右子树答案,合并时右子树每个元素的排名相当于整体平移了左子树大小,于是多贡献
正确性显然,时间复杂度就是 01-trie 的复杂度单次
Code
// Made by Billlly 喵~
#include <bits/stdc++.h>
using i64 = long long;
using u64 = unsigned long long;
constexpr static int mod = 998244353;
constexpr static int B = 29;
struct info {
int ch[2];
int cnt;
int sum;
int ans;
};
std::vector<info> node;
int update(int pre, int bit, int x, int delta) {
int cur = (int)node.size();
node.emplace_back(node[pre]);
if (bit < 0) {
node[cur].cnt += delta;
int c = node[cur].cnt;
int xm = x % mod;
node[cur].sum = (i64)c * xm % mod;
i64 pairs = (i64)c * (c + 1) / 2 % mod;
node[cur].ans = pairs * xm % mod;
return cur;
}
int b = (x >> bit) & 1;
int od = node[pre].ch[b];
int nw = update(od, bit - 1, x, delta);
node[cur].ch[b] = nw;
int l = node[cur].ch[0];
int r = node[cur].ch[1];
node[cur].cnt = node[l].cnt + node[r].cnt;
int s = node[l].sum + node[r].sum;
if (s >= mod)
s -= mod;
node[cur].sum = s;
i64 res = node[l].ans + node[r].ans;
res += (i64)node[l].cnt * node[r].sum % mod;
node[cur].ans = (int)(res % mod);
return cur;
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
node.reserve(20000000);
node.emplace_back(info{});
int n, q;
std::cin >> n >> q;
int root = 0;
for (int i = 1; i <= n; ++i) {
int a;
std::cin >> a;
root = update(root, B, a, 1);
}
while (q--) {
int opt;
std::cin >> opt;
if (opt == 1) {
int x;
std::cin >> x;
root = update(root, B, x, 1);
} else if (opt == 2) {
int x;
std::cin >> x;
root = update(root, B, x, -1);
} else
std::cout << node[root].ans << '\n';
}
return 0;
}