智乃的树旋转 (splay板子)

智乃的树旋转

[Link](H-智乃的树旋转(hard version)_2022牛客寒假算法基础集训营3 (nowcoder.com))

题意

给你一棵二叉树 t r 1 tr1 tr1和一棵被旋转过的二叉树 t r 2 tr2 tr2,让你输出将 t r 2 tr2 tr2转成 t r 1 tr1 tr1的操作序列(每次的旋转轴)。

思路

​ 其实就是 s p l a y splay splay这个数据结构的核心代码旋转,每次 r o t a t e rotate rotate其实是改变一对父子关系,如果将某个点 x x x一直 r o t a t e rotate rotate它最终会到根节点,我们可以遍历 t r 1 tr1 tr1每次将当前的结点 u u u t r 2 tr2 tr2中的位置旋转到当前 t r 1 tr1 tr1的位置,我们先将 t r 1 tr1 tr1根在 t r 2 tr2 tr2中转到根,然后标记一次,再递归左到左右子树即可。

Code

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <set>
#include <queue>
#include <vector>
#include <map>
#include <bitset>
#include <unordered_map>
#include <cmath> 
#include <stack>
#include <iomanip>
#include <deque> 
#include <sstream>
#define x first
#define y second
#define debug(x) cout<<#x<<":"<<x<<endl;
using namespace std;
typedef long double ld;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef unsigned long long ULL;
const int N = 1e2 + 10, M = 2 * N, INF = 0x3f3f3f3f, mod = 1e9 + 7;
const double eps = 1e-8, pi = acos(-1), inf = 1e20;
#define tpyeinput int
inline char nc() {static char buf[1000000],*p1=buf,*p2=buf;return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;}
inline void read(tpyeinput &sum) {char ch=nc();sum=0;while(!(ch>='0'&&ch<='9')) ch=nc();while(ch>='0'&&ch<='9') sum=(sum<<3)+(sum<<1)+(ch-48),ch=nc();}
int n, m, k;
struct Node {
	int s[2], p;
}tr1[N], tr2[N];
int root1, root2;
bool ok[N];
vector<int> res;
void rotate(int x) {
	int y = tr2[x].p, z = tr2[y].p;
	int k = tr2[y].s[1] == x;
	tr2[z].s[tr2[z].s[1] == y] = x, tr2[x].p = z;
	tr2[y].s[k] = tr2[x].s[k ^ 1], tr2[tr2[x].s[k ^ 1]].p = y;
	tr2[x].s[k^1] = y, tr2[y].p = x;
}
void splay(int x) {
	while (!ok[tr2[x].p]) {
		int y = tr2[x].p, z = tr2[y].p;
		if (z && !ok[z])
			if ((tr2[z].s[1] == y) ^ (tr2[y].s[1] == x)) rotate(x), res.push_back(x);
			else rotate(y), res.push_back(y);
		rotate(x), res.push_back(x);
	}
}
void dfs(int u) {
	splay(u);
	ok[u] = true;
	if (tr1[u].s[0]) dfs(tr1[u].s[0]);
	if (tr1[u].s[1]) dfs(tr1[u].s[1]);
}
int main() {
	ios::sync_with_stdio(false), cin.tie(0);
	cin >> n;
	for (int i = 1; i <= n; i ++) {
		int x, y; cin >> x >> y;
		tr1[i].s[0] = x, tr1[i].s[1] = y;
		if (x) tr1[x].p = i;
		if (y) tr1[y].p = i;
	}
	for (int i = 1; i <= n; i ++) {
		int x, y; cin >> x >> y;
		tr2[i].s[0] = x, tr2[i].s[1] = y;
		if (x) tr2[x].p = i;
		if (y) tr2[y].p = i;
	}
	
	for (int i = 1; i <= n; i ++) 
		if (!tr1[i].p) root1 = i;	
	 ok[0] = true;
	 dfs(root1);

	cout << res.size() << endl;

	for (auto x : res) cout << x << " ";
	cout << endl;
		
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值