【BZOJ3223】Tyvj 1729 文艺平衡树【Splay】

【题目链接】

大水题。

/* Telekinetic Forest Guard */
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int maxn = 100005, inf = 0x3f3f3f3f;

int n, m;

int son[maxn][2], pre[maxn], size[maxn], val[maxn];
int root, tot;
bool rev[maxn];

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

inline void newnode(int &x, int f, int c) {
	x = ++tot;
	son[x][0] = son[x][1] = rev[x] = 0;
	pre[x] = f;
	size[x] = 1;
	val[x] = c;
}

inline void pushup(int x) {
	size[x] = size[son[x][0]] + 1 + size[son[x][1]];
}

inline void pushdown(int x) {
	int l = son[x][0], r = son[x][1];
	if(rev[x]) {
		rev[l] ^= 1; rev[r] ^= 1;
		swap(son[l][0], son[l][1]);
		swap(son[r][0], son[r][1]);
		rev[x] = 0;
	}
}

inline void build(int &x, int f, int l, int r) {
	if(l > r) return;
	int mid = l + r >> 1;
	newnode(x, f, mid);
	build(son[x][0], x, l, mid - 1);
	build(son[x][1], x, mid + 1, r);
	pushup(x);
}

inline void init() {
	root = tot = 0;
	son[0][0] = son[0][1] = pre[0] = size[0] = rev[0] = 0;
	newnode(root, 0, -inf);
	newnode(son[root][1], root, inf);
	build(son[son[root][1]][0], son[root][1], 1, n);
	pushup(son[root][1]); pushup(root);
}

inline void rotate(int x) {
	int y = pre[x], z = pre[y], type = son[y][1] == x;
	pre[son[y][type] = son[x][!type]] = y;
	pre[x] = z;
	if(z) son[z][son[z][1] == y] = x;
	pre[son[x][!type] = y] = x;
	pushup(y); pushup(x);
}

inline void splay(int x, int goal) {
	while(pre[x] != goal) {
		int y = pre[x], z = pre[y];
		if(z == goal) rotate(x);
		else if(son[z][1] == y ^ son[y][1] == x) rotate(x), rotate(x);
		else rotate(y), rotate(x);
	}
	if(!goal) root = x;
}

inline int find(int k) {
	int x = root;
	for(pushdown(x); k != size[son[x][0]] + 1; pushdown(x))
		if(k <= size[son[x][0]]) x = son[x][0];
		else k -= size[son[x][0]] + 1, x = son[x][1];
	return x;
}

inline void reverse(int l, int r) {
	int x = find(l), y = find(r + 2);
	splay(x, 0); splay(y, x);
	rev[son[y][0]] ^= 1;
	swap(son[son[y][0]][0], son[son[y][0]][1]);
}

inline void dfs(int x) {
	if(!x) return;
	pushdown(x);
	dfs(son[x][0]);
	printf("%d ", val[x]);
	dfs(son[x][1]);
}

inline void output() {
	splay(1, 0); splay(2, 1);
	dfs(son[2][0]);
}

int main() {
	n = iread(); m = iread();
	init();
	while(m--) {
		int l = iread(), r = iread();
		reverse(l, r);
	}
	output();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值