forked from Dev-XYS/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Link-Cut-Tree(with-Reverse).cpp
164 lines (148 loc) · 2.03 KB
/
Link-Cut-Tree(with-Reverse).cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#include <cstdio>
#define NIL 0
#define N 10010
using namespace std;
int n, m;
int ch[N][2], fa[N], tf[N];
bool rev[N];
inline void swap(int *x)
{
int temp = x[0];
x[0] = x[1];
x[1] = temp;
}
inline int which(int u)
{
return ch[fa[u]][0] == u ? 0 : 1;
}
void rotate(int u)
{
int p = fa[u];
int g = fa[p];
int k1 = which(u), k0 = which(p);
int c = ch[u][k1 ^ 1];
fa[c] = p;
fa[u] = g;
fa[p] = u;
ch[g][k0] = u;
ch[p][k1] = c;
ch[u][k1 ^ 1] = p;
}
void push_down(int u)
{
if (rev[u] == true)
{
swap(ch[u]);
rev[u] = false;
rev[ch[u][0]] ^= true, rev[ch[u][1]] ^= true;
}
}
void splay(int u, int tar)
{
static int path[N];
int pc = 0;
while (u != tar)
{
path[pc++] = u;
u = fa[u];
}
for (int i = pc - 1; i >= 0; i--)
{
push_down(path[i]);
}
u = path[0];
while (fa[u] != tar)
{
if (fa[fa[u]] != tar)
{
if (which(u) == which(fa[u])) rotate(fa[u]);
else rotate(u);
}
rotate(u);
}
}
int find_top(int u)
{
push_down(u);
while (ch[u][0] != NIL)
{
u = ch[u][0];
push_down(u);
}
splay(u, NIL);
return u;
}
int get_root(int u)
{
while (fa[u] != NIL)
{
u = fa[u];
}
return u;
}
void access(int u)
{
int c = NIL;
while (u != NIL)
{
splay(u, NIL);
fa[ch[u][1]] = NIL;
if (ch[u][1] != NIL) tf[find_top(ch[u][1])] = u;
ch[u][1] = c;
fa[c] = u;
c = find_top(u);
u = tf[c];
}
}
void change_root(int u)
{
access(u);
splay(u, NIL);
rev[u] = true;
find_top(u);
tf[u] = NIL;
}
void link(int u, int v)
{
change_root(v);
tf[v] = u;
}
void cut(int u, int v)
{
change_root(u);
access(v);
splay(u, NIL);
fa[v] = NIL;
ch[u][1] = NIL;
tf[v] = NIL;
}
bool query(int u, int v)
{
change_root(u);
access(v);
if (get_root(u) == get_root(v)) return true;
else return false;
}
int main()
{
char op[10];
int u, v;
scanf("%d%d", &n, &m);
while (m--)
{
scanf("%s%d%d", op, &u, &v);
if (op[0] == 'C')
{
link(u, v);
}
else if (op[0] == 'D')
{
cut(u, v);
}
else
{
printf("%s\n", query(u, v) == true ? "Yes" : "No");
}
}
return 0;
}