AcWing2437. Splay 题解
题目链接:https://www.acwing.com/problem/content/description/2439/
题目大意:splay 执行区间翻转
示例程序:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
int n, m;
struct Node {
int s[2], p, v;
int sz, flag;
Node() {};
Node(int _v, int _p) {v = _v; p = _p; s[0] = s[1] = 0; flag = 0; sz = 1;}
} tr[maxn];
int root, idx;
void push_up(int x) {
tr[x].sz = tr[tr[x].s[0]].sz + tr[tr[x].s[1]].sz + 1;
}
void t_swap(int x) {
tr[x].flag ^= 1;
swap(tr[x].s[0], tr[x].s[1]);
}
void push_down(int x) {
if (tr[x].flag) {
t_swap(tr[x].s[0]);
t_swap(tr[x].s[1]);
tr[x].flag = 0;
}
}
void f_s(int p, int u, bool k) {
tr[p].s[k] = u;
tr[u].p = p;
}
void rot(int x) {
int y = tr[x].p, z = tr[y].p;
bool k = tr[y].s[1] == x;
f_s(z, x, tr[z].s[1]==y);
f_s(y, tr[x].s[k^1], k);
f_s(x, y, k^1);
push_up(y), push_up(x);
}
void splay(int x, int k) {
while (tr[x].p != k) {
int y = tr[x].p, z = tr[y].p;
if (z != k)
(tr[y].s[1]==x) ^ (tr[z].s[1]==y) ? rot(x) : rot(y);
rot(x);
}
if (!k) root = x;
}
void ins(int v) {
int u = root, p = 0;
while (u) {
p = u, u = tr[u].s[v > tr[u].v];
}
tr[u = ++idx] = Node(v, p);
if (p) tr[p].s[v > tr[p].v] = u;
splay(u, 0);
}
int get_k(int k) {
int u = root;
while (u) {
push_down(u);
if (tr[tr[u].s[0]].sz >= k) u = tr[u].s[0];
else if (tr[tr[u].s[0]].sz + 1 == k) return u;
else k -= tr[tr[u].s[0]].sz + 1, u = tr[u].s[1];
}
return -1;
}
void output(int u) {
if (!u) return;
push_down(u);
output(tr[u].s[0]);
if (tr[u].v >= 1 && tr[u].v <= n) printf("%d ", tr[u].v);
output(tr[u].s[1]);
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i <= n+1; i++) {
ins(i);
}
while (m--) {
int l, r;
scanf("%d%d", &l, &r);
l = get_k(l), r = get_k(r+2);
splay(l, 0), splay(r, l);
t_swap(tr[r].s[0]);
}
output(root);
return 0;
}