线性序列并查集 / P1840 Color the Axis 题解
August_Light · · 个人记录
P1840 Color the Axis
线性复杂度。
考虑均摊。此题可以精简为以下两个操作:
- 把黑点变成白点。
- 找到一个点右边第一个黑点的位置(包括自身)。
直接路径压缩可以做到
为了优化到
以块长为
时间复杂度
#include <bits/stdc++.h>
#define ctz __builtin_ctz
using namespace std;
typedef long long ll;
const int MAXN = 2e5 + 5;
const int B = 30;
int n, m;
int fa[MAXN / B + 5], b[MAXN / B + 5];
void init() {
for (int i = 0; i <= n / B; i++)
fa[i] = i, b[i] = (1 << B) - 1;
}
int find(int u) {
if (fa[u] == u)
return u;
return fa[u] = find(fa[u]);
}
int query(int x) { // 查询 x 右边第一个黑点的位置
int p = x / B, q = x % B;
int tmp = b[p];
if (!(b[p] >> q)) {
p = find(p + 1);
tmp = b[p];
q = 0;
}
return ctz(tmp >> q << q) + p * B;
}
void merge(int x) { // 把 x 从黑点变成白点
int p = x / B, q = x % B;
b[p] ^= 1 << q;
if (!b[p])
fa[p] = find(p+1);
}
int main() { ios::sync_with_stdio(0); cin.tie(0);
cin >> n >> m;
init();
int ans = n;
while (m--) {
int l, r; cin >> l >> r;
int t = query(l);
while (t <= r) {
merge(t);
t = query(t);
ans--;
}
cout << ans << '\n';
}
return 0;
}
参考:
- RMQ标准算法和线性树上并查集 - 博客 - ljt12138的博客
- 序列线性并查集 - qwq - 洛谷博客