-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathOperations on Tree.cpp
91 lines (72 loc) · 2.39 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Runtime: 452 ms (Top 31.8%) | Memory: 134.50 MB (Top 43.59%)
class LockingTree {
public:
unordered_map<int, vector<int>> descendents;
vector<vector<int>> Node;
/*
Node[i][0] = parent[i]
Node[i][1] = -1; (means unlocked)
Node[i][1] = x; (means locked by user x)
*/
int n;
LockingTree(vector<int>& parent) {
n = parent.size();
Node.resize(n, vector<int>(2, -1));
Node[0][0] = -1; //root has no parent
for(int i = 1; i<n; i++) {
Node[i][0] = parent[i];
descendents[parent[i]].push_back(i);
}
}
bool lock(int num, int user) {
if(Node[num][1] != -1) return false;
Node[num][1] = user;
return true;
}
bool unlock(int num, int user) {
if(Node[num][1] != user) return false;
Node[num][1] = -1;
return true;
}
//Condition-2 (Atleast one descendent should be locked)
void checkDescendents(int num, bool& atleastOne) {
if(descendents.count(num) == 0 || descendents[num].size() == 0)
return;
for(int& x : descendents[num]) {
if(Node[x][1] != -1) {
atleastOne = true;
return;
}
checkDescendents(x, atleastOne);
}
}
//Condition-3 (Check if any ancestor is locked)
bool IsAnyAncestorLocked(int& num) {
if(num == -1)
return false; //you reached end and found none locked
return Node[num][1] != -1 || IsAnyAncestorLocked(Node[num][0]);
}
void unlockDescendents(int num) {
if(descendents.count(num) == 0 || descendents[num].size() == 0)
return;
for(int& x : descendents[num]) {
Node[x][1] = -1;
unlockDescendents(x);
}
}
bool upgrade(int num, int user) {
//condition : 1
if(Node[num][1] != -1) return false;
//condition : 2
bool atleastOne = false;
checkDescendents(num, atleastOne);
//If no node was locked, return false
if(!atleastOne) return false;
//condition : 3
if(IsAnyAncestorLocked(Node[num][0])) return false;
//Do the rest
unlockDescendents(num);
Node[num][1] = user;
return true;
}
};