forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
58 lines (52 loc) · 1.43 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
class LockingTree {
public:
unordered_map<int, int> nums;
vector<int> parent;
vector<vector<int>> children;
LockingTree(vector<int>& parent) {
this->parent = parent;
int n = parent.size();
children.resize(n);
for (int i = 0; i < n; ++i)
if (parent[i] != -1)
children[parent[i]].push_back(i);
}
bool lock(int num, int user) {
if (nums.count(num)) return false;
nums[num] = user;
return true;
}
bool unlock(int num, int user) {
if (!nums.count(num) || nums[num] != user) return false;
nums.erase(num);
return true;
}
bool upgrade(int num, int user) {
for (int t = num; t != -1; t = parent[t])
if (nums.count(t))
return false;
bool find = false;
dfs(num, find);
if (!find) return false;
nums[num] = user;
return true;
}
void dfs(int num, bool& find) {
for (int child : children[num])
{
if (nums.count(child))
{
nums.erase(child);
find = true;
}
dfs(child, find);
}
}
};
/**
* 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);
*/