Title Link: BZOJ-2049
Problem analysis
The basic model of LCT, including Link, Cut operation and judging whether two points are within the same tree.
Link (x, y): Make_root (x); Splay (x); Father[x] = y;
Cut (x, y): Make_root (x); Access (y); Break down Y and son[y][0]; Note Modify the IsRoot and Father of Son[y][0]
To determine if x, Y are within the same number, we will see if the root of the tree at two points is the same, using find_root ();
Find_root (x): Access (x); Splay (x); while (son[x][0]! = 0) x = son[x][0]; Then x is the root of the tree.
Code
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <cmath > #include <algorithm>using namespace std;inline void Read (int &num) {char c = getchar (); bool Neg = False;while (C < ' 0 ' | | c > ' 9 ') {if (c = = '-') Neg = True;c = GetChar ();} Num = C-' 0 '; c = GetChar (); while (c >= ' 0 ' && C <= ' 9 ') {num = num * + C-' 0 '; c = GetChar ();} if (Neg) Num =-num;} const int MAXN = 10000 + 5;int N, m;int Father[maxn], Son[maxn][2];bool ISROOT[MAXN], rev[maxn];inline void Reverse (int x) {Rev[x] =! Rev[x];swap (Son[x][0], son[x][1]);} inline void pushdown (int x) {if (! REV[X]) return; REV[X] = false;if (son[x][0]) Reverse (son[x][0]), if (son[x][1]) Reverse (son[x][1]);} void Rotate (int x) {int y = father[x], F; Pushdown (y); Pushdown (x); if (x = = Son[y][0]) F = 1;else f = 0;if (Isroot[y]) {isroot[y] = false;isroot[x] = true;} Else{if (y = = son[father[y]][0]) son[father[y]][0] = X;else son[father[y]][1] = x;} FATHER[X] = Father[y]; Son[y][f ^ 1] = Son[x][f];if (Son[x][f]) father[son[x][f]] = y; Son[x][f] = y; Father[y] = x;} void splay (int x) {int y;while (!isroot[x]) {y = father[x];if (Isroot[y]) {Rotate (x); break;} if (y = = Son[father[y]][0]) {if (x = = Son[y][0]) {Rotate (y); Rotate (x);} Else{rotate (x); Rotate (x);}} Else{if (x = = Son[y][1]) {Rotate (y); Rotate (x);} Else{rotate (x); Rotate (x);}}} int Access (int x) {int y = 0;while (x! = 0) {splay (x); Pushdown (x); isroot[son[x][1]] = true; SON[X][1] = y;if (y) isroot[y] = False;y = X;x = Father[x];} return y;} void make_root (int x) {int t = Access (x); Reverse (t);} int find_root (int x) {int t = Access (x); while (son[t][0]! = 0) T = Son[t][0];return t;} int main () {scanf ("%d%d", &n, &m); for (int i = 1; I <= n; ++i) {isroot[i] = true; Father[i] = 0;} Char Str[10];int A, B, X, y;for (int i = 1; I <= m; ++i) {scanf ("%s", STR); Read (a); Read (b); if (strcmp (Str, "Connect") = = 0) {make_root (a); Splay (a); Father[a] = b;} else if (strcmp (Str, "Destroy") = = 0) {make_root (a); Access (b); Splay (b); Pushdown (b); isRoOt[son[b][0]] = true; Father[son[b][0]] = 0; Son[b][0] = 0;} Else{x = Find_root (a), y = Find_root (b), if (x = = y) printf ("yes\n"), Else printf ("no\n");}} return 0;}
[Bzoj 2049] [Sdoi2008] Cave Cave Survey "LCT"