-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.ts
66 lines (61 loc) · 1.65 KB
/
Solution.ts
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
class LockingTree {
private locked: number[];
private parent: number[];
private children: number[][];
constructor(parent: number[]) {
const n = parent.length;
this.locked = Array(n).fill(-1);
this.parent = parent;
this.children = Array(n)
.fill(0)
.map(() => []);
for (let i = 1; i < n; i++) {
this.children[parent[i]].push(i);
}
}
lock(num: number, user: number): boolean {
if (this.locked[num] === -1) {
this.locked[num] = user;
return true;
}
return false;
}
unlock(num: number, user: number): boolean {
if (this.locked[num] === user) {
this.locked[num] = -1;
return true;
}
return false;
}
upgrade(num: number, user: number): boolean {
let x = num;
for (; x !== -1; x = this.parent[x]) {
if (this.locked[x] !== -1) {
return false;
}
}
let find = false;
const dfs = (x: number) => {
for (const y of this.children[x]) {
if (this.locked[y] !== -1) {
this.locked[y] = -1;
find = true;
}
dfs(y);
}
};
dfs(num);
if (!find) {
return false;
}
this.locked[num] = user;
return true;
}
}
/**
* Your LockingTree object will be instantiated and called as such:
* var obj = new LockingTree(parent)
* var param_1 = obj.lock(num,user)
* var param_2 = obj.unlock(num,user)
* var param_3 = obj.upgrade(num,user)
*/