-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.cpp
67 lines (62 loc) · 1.61 KB
/
Solution.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
class LockingTree {
public:
LockingTree(vector<int>& parent) {
int n = parent.size();
locked = vector<int>(n, -1);
this->parent = parent;
children.resize(n);
for (int i = 1; i < n; ++i) {
children[parent[i]].push_back(i);
}
}
bool lock(int num, int user) {
if (locked[num] == -1) {
locked[num] = user;
return true;
}
return false;
}
bool unlock(int num, int user) {
if (locked[num] == user) {
locked[num] = -1;
return true;
}
return false;
}
bool upgrade(int num, int user) {
int x = num;
while (x != -1) {
if (locked[x] != -1) {
return false;
}
x = parent[x];
}
bool find = false;
function<void(int)> dfs = [&](int x) {
for (int y : children[x]) {
if (locked[y] != -1) {
find = true;
locked[y] = -1;
}
dfs(y);
}
};
dfs(num);
if (!find) {
return false;
}
locked[num] = user;
return true;
}
private:
vector<int> locked;
vector<int> parent;
vector<vector<int>> children;
};
/**
* Your LockingTree object will be instantiated and called as such:
* LockingTree* obj = new LockingTree(parent);
* bool param_1 = obj->lock(num,user);
* bool param_2 = obj->unlock(num,user);
* bool param_3 = obj->upgrade(num,user);
*/