3
Map<Integer, Integer> map = new HashMap<>();4
Map<Integer, List<Integer>> children = new HashMap<>();6
public LockingTree(int[] parent) {8
for (int i = 0; i < p.length; i++) {9
children.put(i, new ArrayList<>());11
for (int i = 1; i < p.length; i++) {12
children.get(p[i]).add(i);16
public boolean lock(int num, int user) {17
if (!map.containsKey(num)) {24
public boolean unlock(int num, int user) {25
if (map.containsKey(num) && map.get(num) == user) {32
public boolean upgrade(int num, int user) {34
if (map.containsKey(num)) return false;37
while (p[num] != -1) {38
if (map.get(p[num]) != null) return false;42
Queue<Integer> q = new LinkedList<>();43
List<Integer> child = children.get(ori);45
for (int c : child) q.offer(c);48
while (!q.isEmpty()) {50
if (map.get(cur) != null) {52
map.remove(cur); // unlock54
List<Integer> cc = children.get(cur);56
for (int c : cc) q.offer(c);59
if (!lock) return false;60
map.put(ori, user); // lock the original node