-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkcut.cpp
More file actions
158 lines (139 loc) · 2.57 KB
/
linkcut.cpp
File metadata and controls
158 lines (139 loc) · 2.57 KB
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
struct Node
{ int sz, label; /* size, label */
Node *p, *pp, *l, *r; /* parent, path-parent, left, right pointers */
Node() { p = pp = l = r = 0; }
};
void update(Node *x)
{ x->sz = 1;
if(x->l) x->sz += x->l->sz;
if(x->r) x->sz += x->r->sz;
}
void rotr(Node *x)
{ Node *y, *z;
y = x->p, z = y->p;
if((y->l = x->r)) y->l->p = y;
x->r = y, y->p = x;
if((x->p = z))
{ if(y == z->l) z->l = x;
else z->r = x;
}
x->pp = y->pp;
y->pp = 0;
update(y);
}
void rotl(Node *x)
{ Node *y, *z;
y = x->p, z = y->p;
if((y->r = x->l)) y->r->p = y;
x->l = y, y->p = x;
if((x->p = z))
{ if(y == z->l) z->l = x;
else z->r = x;
}
x->pp = y->pp;
y->pp = 0;
update(y);
}
void splay(Node *x)
{ Node *y, *z;
while(x->p)
{ y = x->p;
if(y->p == 0)
{ if(x == y->l) rotr(x);
else rotl(x);
}
else
{ z = y->p;
if(y == z->l)
{ if(x == y->l) rotr(y), rotr(x);
else rotl(x), rotr(x);
}
else
{ if(x == y->r) rotl(y), rotl(x);
else rotr(x), rotl(x);
}
}
}
update(x);
}
Node *access(Node *x)
{ splay(x);
if(x->r)
{ x->r->pp = x;
x->r->p = 0;
x->r = 0;
update(x);
}
Node *last = x;
while(x->pp)
{ Node *y = x->pp;
last = y;
splay(y);
if(y->r)
{ y->r->pp = y;
y->r->p = 0;
}
y->r = x;
x->p = y;
x->pp = 0;
update(y);
splay(x);
}
return last;
}
Node *root(Node *x)
{ access(x);
while(x->l) x = x->l;
splay(x);
return x;
}
void cut(Node *x)
{ access(x);
x->l->p = 0;
x->l = 0;
update(x);
}
void link(Node *x, Node *y)
{ access(x);
access(y);
x->l = y;
y->p = x;
update(x);
}
Node *lca(Node *x, Node *y)
{ access(x);
return access(y);
}
int depth(Node *x)
{ access(x);
return x->sz - 1;
}
class LinkCut
{ Node *x;
public:
LinkCut(int n)
{ x = new Node[n];
for(int i = 0; i < n; i++)
{ x[i].label = i;
update(&x[i]);
}
}
virtual ~LinkCut()
{ delete[] x;
}
void link(int u, int v)
{ ::link(&x[u], &x[v]);
}
void cut(int u)
{ ::cut(&x[u]);
}
int root(int u)
{ return ::root(&x[u])->label;
}
int depth(int u)
{ return ::depth(&x[u]);
}
int lca(int u, int v)
{ return ::lca(&x[u], &x[v])->label;
}
};