forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.py
47 lines (41 loc) · 1.29 KB
/
Solution.py
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
class LockingTree:
def __init__(self, parent: List[int]):
self.nums = {}
self.parent = parent
self.children = defaultdict(list)
for i, p in enumerate(parent):
self.children[p].append(i)
def lock(self, num: int, user: int) -> bool:
if num in self.nums:
return False
self.nums[num] = user
return True
def unlock(self, num: int, user: int) -> bool:
if num not in self.nums or self.nums[num] != user:
return False
self.nums.pop(num)
return True
def upgrade(self, num: int, user: int) -> bool:
def dfs(num):
nonlocal find
for child in self.children[num]:
if child in self.nums:
self.nums.pop(child)
find = True
dfs(child)
t = num
while t != -1:
if t in self.nums:
return False
t = self.parent[t]
find = False
dfs(num)
if not find:
return False
self.nums[num] = user
return True
# Your LockingTree object will be instantiated and called as such:
# obj = LockingTree(parent)
# param_1 = obj.lock(num,user)
# param_2 = obj.unlock(num,user)
# param_3 = obj.upgrade(num,user)