Created
September 12, 2021 02:17
-
-
Save HarshKumarChoudary/f35aa90ffc16e38c861db9495bcc4252 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LockingTree { | |
private: | |
vector<int>parent; | |
map<int,vector<int>>children; | |
map<int,int>lockby; | |
public: | |
LockingTree(vector<int>& p):parent(p) { | |
for(int i = 0;i<p.size();++i){ | |
children[p[i]].push_back(i); | |
} | |
} | |
bool lock(int num, int user) { | |
if(lockby.find(num)!=lockby.end()) | |
return false; | |
lockby[num]=user; | |
return true; | |
} | |
bool unlock(int num, int user) { | |
if(lockby.find(num)==lockby.end()) | |
return false; | |
if(lockby[num]!=user) | |
return false; | |
lockby.erase(num); | |
return true; | |
} | |
bool checkparent(int num){ | |
if(num==-1)return false; | |
if(lockby.find(num)!=lockby.end()) | |
return true; | |
return checkparent(parent[num]); | |
} | |
bool checkchild(int num){ | |
bool flag = false; | |
if(lockby.find(num)!=lockby.end()) | |
flag = true; | |
for(auto ch:children[num]) | |
flag |= checkchild(ch); | |
return flag; | |
} | |
void unlockchild(int num){ | |
for(auto ch:children[num]){ | |
lockby.erase(ch); | |
unlockchild(ch); | |
} | |
} | |
bool upgrade(int num, int user) { | |
if(lockby.find(num)!=lockby.end()) | |
return false; | |
if(checkchild(num) and !checkparent(num)) | |
{ | |
unlockchild(num); | |
lockby[num]=user; | |
return true; | |
} | |
return false; | |
} | |
}; | |
/** | |
* 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); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment