空间树 – 锁定和解锁 N 叉树
给定一个由N个节点和一个数组queries[]组成的 Generic M-ary Tree 形式的世界地图,任务是为给定的树实现Lock 、 Unlock和Upgrade函数。对于 query []中的每个查询,当操作执行成功时,函数返回true ,否则返回false 。函数定义为:
X:树中节点的名称,并且是唯一的
uid:访问节点 X 的人的用户 ID
1. Lock(X, uid): Lock 独占访问以根为根的子树。
- 一旦Lock(X, uid)成功,那么lock(A, any user)应该会失败,其中A是X的后代。
- Lock(B. any user)在X是B的后代的情况下应该失败。
- 不能对已经被锁定的节点进行锁定操作。
2. Unlock(X, uid):解锁被锁定的节点。
- 解锁恢复了锁定操作所做的事情。
- 它只能由相同的uid调用和解锁。
3. UpgradeLock(X, uid):用户uid可以将自己的锁升级到祖先节点。
- 仅当任何祖先节点仅由同一用户uid锁定时才有可能。
- 如果有任何节点被下面的某个其他uid Y锁定,则升级应该会失败。
例子:
Input: N = 7, M = 2, nodes = [‘World’, ‘Asia’, ‘Africa’, ‘China’, ‘India’, ‘SouthAfrica’, ‘Egypt’],
queries = [‘1 China 9’, ‘1 India 9’, ‘3 Asia 9’, ‘2 India 9’, ‘2 Asia 9’]
Output: true true true false true
Input: N = 3, M = 2, nodes = [‘World’, ‘China’, ‘India’],
queries = [‘3 India 1’, ‘1 World 9’]
Output: false true
下面是上述方法的实现:
Python3
# Python Implementation
# Locking function
def lock(name):
ind = nodes.index(name)+1
c1 = ind * 2
c2 = ind * 2 + 1
if status[name] == 'lock' \
or status[name] == 'fail':
return 'false'
else:
p = ind//2
status[nodes[p-1]] = 'fail'
status[name] = 'lock'
return 'true'
# Unlocking function
def unlock(name):
if status[name] == 'lock':
status[name] = 'unlock'
return 'true'
else:
return 'false'
# Upgrade function
def upgrade(name):
ind = nodes.index(name)+1
# left child of ind
c1 = ind * 2
# right child of ind
c2 = ind * 2 + 1
if c1 in range(1, n) and c2 in range(1, n):
if status[nodes[c1-1]] == 'lock' \
and status[nodes[c2-1]] == 'lock':
status[nodes[c1-1]] = 'unlock'
status[nodes[c2-1]] = 'unlock'
status[nodes[ind-1]] = 'lock'
return 'true'
else:
return 'false'
# Precomputation
def precompute(queries):
d = []
# Traversing the queries
for j in queries:
i = j.split()
d.append(i[1])
d.append(int(i[0]))
status = {}
for j in range(0, len(d)-1, 2):
status[d[j]] = 0
return status, d
# Function to perform operations
def operation(name, code):
result = 'false'
# Choose operation to perform
if code == 1:
result = lock(name)
elif code == 2:
result = unlock(name)
elif code == 3:
result = upgrade(name)
return result
# Driver Code
if __name__ == '__main__':
# Given Input
n = 7;m = 2
apis = 5
nodes = ['World', 'Asia', \
'Africa', 'China', \
'India', 'SouthAfrica', 'Egypt']
queries = ['1 China 9', '1 India 9', \
'3 Asia 9', '2 India 9', '2 Asia 9']
# Precomputation
status, d = precompute(queries)
# Function Call
for j in range(0, len(d) - 1, 2):
print(operation(d[j], d[j + 1]), end = ' ')
true true true false true
时间复杂度: O(LogN)
辅助空间: O(N)