- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 58 lines of C++ from the credited upstream file 1993.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1struct Node {2 vector<int> children;3 int lockedBy = -1;4};5 6class LockingTree {7 public:8 LockingTree(vector<int>& parent) : parent(parent) {9 nodes.resize(parent.size());10 for (int i = 1; i < parent.size(); ++i)11 nodes[parent[i]].children.push_back(i);12 }13 14 bool lock(int num, int user) {15 if (nodes[num].lockedBy != -1)16 return false;17 return nodes[num].lockedBy = user;18 }19 20 bool unlock(int num, int user) {21 if (nodes[num].lockedBy != user)22 return false;23 return nodes[num].lockedBy = -1;24 }25 26 bool upgrade(int num, int user) {27 if (nodes[num].lockedBy != -1)28 return false;29 if (!anyLockedDescendant(num))30 return false;31 32 33 for (int i = num; i != -1; i = parent[i])34 if (nodes[i].lockedBy != -1)35 return false;36 37 unlockDescendants(num);38 return nodes[num].lockedBy = user;39 }40 41 private:42 const vector<int> parent;43 vector<Node> nodes;44 45 bool anyLockedDescendant(int i) {46 return nodes[i].lockedBy != -1 ||47 ranges::any_of(nodes[i].children, [this](const int child) {48 return anyLockedDescendant(child);49 });50 }51 52 void unlockDescendants(int i) {53 nodes[i].lockedBy = -1;54 for (const int child : nodes[i].children)55 unlockDescendants(child);56 }57};58