-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkcut.go
More file actions
47 lines (41 loc) · 1017 Bytes
/
linkcut.go
File metadata and controls
47 lines (41 loc) · 1017 Bytes
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
package linkcut
import "github.com/JonathanYuan23/link-cut-tree/splay"
// MakeTree returns a new node as a singleton tree
func MakeTree() *splay.Node {
return splay.NewNode()
}
// Link adds c as a child of p. Assumes that c is the root of
// its own tree
func Link(c, p *splay.Node) {
c.Access()
p.Access()
c.Attach(0, p)
}
// Cut detaches n from its parent
func Cut(n *splay.Node) {
n.Access()
n.Detach(0, n.PathParent)
n.Child[0] = nil
// n becomes the root of its own represented tree
n.PathParent = nil
}
// FindRoot finds the root of the represented tree containing n.
// This operation may be time-consuming because the path to the root
// could be very long
func FindRoot(n *splay.Node) *splay.Node {
n.Access()
m := n
for ; m.Child[0] != nil; m = m.Child[0] {
}
m.Access()
return m
}
// LCA returns the lowest common ancestor of n and m in the
// represented tree.
func LCA(n, m *splay.Node) *splay.Node {
if FindRoot(n) != FindRoot(m) {
return nil
}
n.Access()
return m.Access()
}