-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.go
68 lines (63 loc) · 1.27 KB
/
Solution.go
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
type LockingTree struct {
locked []int
parent []int
children [][]int
}
func Constructor(parent []int) LockingTree {
n := len(parent)
locked := make([]int, n)
for i := range locked {
locked[i] = -1
}
children := make([][]int, n)
for i := 1; i < n; i++ {
children[parent[i]] = append(children[parent[i]], i)
}
return LockingTree{locked, parent, children}
}
func (this *LockingTree) Lock(num int, user int) bool {
if this.locked[num] == -1 {
this.locked[num] = user
return true
}
return false
}
func (this *LockingTree) Unlock(num int, user int) bool {
if this.locked[num] == user {
this.locked[num] = -1
return true
}
return false
}
func (this *LockingTree) Upgrade(num int, user int) bool {
x := num
for ; x != -1; x = this.parent[x] {
if this.locked[x] != -1 {
return false
}
}
find := false
var dfs func(int)
dfs = func(x int) {
for _, y := range this.children[x] {
if this.locked[y] != -1 {
find = true
this.locked[y] = -1
}
dfs(y)
}
}
dfs(num)
if !find {
return false
}
this.locked[num] = user
return true
}
/**
* Your LockingTree object will be instantiated and called as such:
* obj := Constructor(parent);
* param_1 := obj.Lock(num,user);
* param_2 := obj.Unlock(num,user);
* param_3 := obj.Upgrade(num,user);
*/