forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
operations-on-tree.cpp
63 lines (58 loc) · 1.54 KB
/
operations-on-tree.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
// Time: ctor: O(n)
// lock: O(1)
// unlock: O(1)
// upgrade: O(n)
// Space: O(n)
class LockingTree {
public:
LockingTree(vector<int>& parent)
: parent_(parent)
, children_(size(parent)) {
for (int i = 0; i < size(parent); ++i) {
if (parent[i] != -1) {
children_[parent_[i]].emplace_back(i);
}
}
}
bool lock(int num, int user) {
if (locked_.count(num)) {
return false;
}
locked_[num] = user;
return true;
}
bool unlock(int num, int user) {
if (!locked_.count(num) || locked_[num] != user) {
return false;
}
locked_.erase(num);
return true;
}
bool upgrade(int num, int user) {
for (int node = num; node != -1; node = parent_[node]) {
if (locked_.count(node)) {
return false;
}
}
bool result = false;
vector<int> stk = {num};
while (!empty(stk)) {
auto node = stk.back(); stk.pop_back();
for (const auto& child : children_[node]) {
if (locked_.count(child)) {
locked_.erase(child);
result = true;
}
stk.emplace_back(child);
}
}
if (result) {
locked_[num] = user;
}
return result;
}
private:
const vector<int>& parent_;
vector<vector<int>> children_;
unordered_map<int, int> locked_;
};