跳到正文

剪贴板

剪贴板 4uwx0nyr

原文
剪贴板信息

剪贴板信息

收录
更新

splay 文艺平衡树

C++
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
#define FL(a, b, c) for(int a = (b), a##end = (c); a <= a##end; a++)
#define FR(a, b, c) for(int a = (b), a##end = (c); a >= a##end; a--)
#define lowbit(x) ((x) & -(x))
constexpr int N = 1e5 + 10;
struct Splay{
	struct node{int size, val, ch[2], fa, lazy;}d[N];
	#define ls(x) d[x].ch[0]
	#define rs(x) d[x].ch[1]
	#define fa(x) d[x].fa
	int root, tot = 0, stk[N], top;
	int newnode(int val){
		int w = top ? stk[top--] : ++tot;
		d[w].size = 1, d[w].val = val, d[w].lazy = ls(w) = rs(w) = fa(w) = 0;
		return w;
	}
	void pushdown(int x){
		if(!d[x].lazy)return;
		swap(ls(x), rs(x)), d[ls(x)].lazy ^= 1, d[rs(x)].lazy ^= 1;
		d[x].lazy = 0;
	}
	void pushup(int x){d[x].size = 1 + d[ls(x)].size + d[rs(x)].size;}
	#define delnode(x) stk[++top] = x
	bool get(int x){return x == rs(fa(x));}
	void rotate(int x){
		int y = fa(x), z = fa(y), c = get(x);
		if(d[x].ch[!c])fa(d[x].ch[!c]) = y;
		d[y].ch[c] = d[x].ch[!c], d[x].ch[!c] = y, fa(y) = x, fa(x) = z;
		if(z) d[z].ch[y == d[z].ch[1]] = x;
		pushup(y), pushup(x);
	}
	void splay(int x, int p){
		for(int f = fa(x); f = fa(x), (f ^ p); rotate(x))
			if(fa(f) ^ p)rotate(get(f) == get(x) ? f : x);
		if(!p)root = x;
	}
	int find(int k){
		int now = root, siz;k++;
		while(now){
			pushdown(now);
			if((siz = d[ls(now)].size + 1) > k) now = ls(now);
			else if(!(k -= siz)) break;
			else now = rs(now);
		}
		return now;
	}
	void print(int now){
		pushdown(now);
		if(ls(now)) print(ls(now));
		if(d[now].val) cout << d[now].val << " ";
		if(rs(now)) print(rs(now));
	}
	void build(int n){
		root = newnode(0);
		for(int i = 1, now = root; i <= n + 1; i++, now = rs(now))
		d[now].size = n + 3 - i, rs(now) = newnode(i > n ? 0 : i), fa(rs(now)) = now;
	}
	void reverse(int l, int r){
		splay(l = find(l - 1), 0), splay(r = find(r + 1), root);
		d[ls(rs(root))].lazy ^= 1;
	}
}T;
int32_t main(){
	cin.tie(0)->sync_with_stdio(0);
	int n, m;
	cin >> n >> m;
	T.build(n);
	while(m--){
		int l, r;
		cin >> l >> r;
		T.reverse(l, r);
	}
	T.print(T.root);
	return 0;
}