【题解】LuoGu3165: [CQOI2014]排序机械臂

博客围绕一道题展开,指出翻转操作意味着使用Splay算法。需先按顺序将元素加入Splay,分析每个元素pi前元素的两种情况,求pi只需在二叉树中找到对应点旋到根,左儿子的size+1就是答案,其余为模板,同时提醒注意细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题传送门
翻转就意味着Splay
然后肯定是先按顺序加入splay
首先找一找这道题有没有什么特点
发现每一个 p i pi pi,在它前面的,两种情况:

  • 权值比自己小,说明肯定在自己之前翻转到自己前面
  • 权值比自己大,但位置在自己前面,这一点用splay维护翻转没毛病

总的来说,求pi很简单,其实只要把pi在二叉树中对应的点找到,旋到根,左儿子的size+1就是答案,其他的就是模板了

细节还是要注意一下

Code:

#include <bits/stdc++.h>
#define maxn 100010
#define inf 1 << 29
using namespace std;
int rt, sz, n, q[maxn];
int size[maxn], recy[maxn], son[maxn][2], tag[maxn], f[maxn];
struct node{
	int v, id;
}a[maxn];

inline int read(){
	int s = 0, w = 1;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
	for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
	return s * w;
}

bool cmp(node x, node y){ return x.v == y.v ? x.id < y.id : x.v < y.v; }

void update(int x){
	if (x){
		size[x] = recy[x];
		if (son[x][0]) size[x] += size[son[x][0]];
		if (son[x][1]) size[x] += size[son[x][1]];
	}
}

int get(int x){ return son[f[x]][1] == x; }

void connect(int x, int y, int z){
	if (x) f[x] = y;
	if (y) son[y][z] = x;
}

void rotate(int x){
	int fa = f[x], ffa = f[fa], m = get(x), n = get(fa);
	connect(son[x][m ^ 1], fa, m);
	connect(fa, x, m ^ 1);
	connect(x, ffa, n);
	update(fa); update(x);
}

void pushdown(int x){
	if (tag[x]){
		tag[x] = 0;
		tag[son[x][0]] ^= 1;
		tag[son[x][1]] ^= 1;
		swap(son[x][0], son[x][1]);
	}
}

void splay(int x, int goal){
	int len = 0;
	for (int i = x; i; i = f[i]) q[++len] = i;
	for (int i = len; i; --i) pushdown(q[i]);
	while (f[x] != goal){
		int fa = f[x];
		if (f[fa] != goal) rotate(get(x) == get(fa) ? fa : x);
		rotate(x);
	}
	if (!goal) rt = x;
}

void build(int l, int r, int fa){
	if (l > r) return;
	int mid = (l + r) >> 1;
	if (mid < fa) son[fa][0] = mid; else son[fa][1] = mid;
	size[mid] = recy[mid] = 1, f[mid] = fa;
	if (l == r) return;
	build(l, mid - 1, mid);
	build(mid + 1, r, mid);
	update(mid);
}

int kth(int x){
	int now = rt;
	while (1){
		pushdown(now);
		if (size[son[now][0]] >= x) now = son[now][0]; else
		if (size[son[now][0]] + 1 == x) return now; else
		x -= size[son[now][0]] + 1, now = son[now][1];
	}
}

void work(int l, int r){
	l = kth(l), r = kth(r + 2);
	splay(l, 0); splay(r, l);
	tag[son[r][0]] ^= 1;
}

int main(){
	n = read();
	for (int i = 2; i <= n + 1; ++i){
		a[i].v = read(), a[i].id = i;
	}
	a[1].id = 1, a[n + 2].id = n + 2;
	a[1].v = -inf, a[n + 2].v = inf;
	sort(a + 1, a + 3 + n, cmp);
    build(1, n + 2, 0);
    rt = (n + 3) >> 1;
	for (int i = 2; i <= n; ++i){
		splay(a[i].id, 0);
		printf("%d ", size[son[rt][0]] + 1 - 1);
		work(i - 1, size[son[rt][0]] + 1 - 1);
	}
	printf("%d\n", n);
	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值