(base) asvinir@Asvinis-MacBook-Air learnDsa % /opt/homebrew/bin/python3 "/Users/asvinir/Library/Mobile Documents/com~apple~CloudDocs/Downloads/learnDsa/test.py"
Running Test Case 1: Locking a Node When an Ancestor is Locked
Test Case 1 Passed

Running Test Case 2: Locking a Node When a Descendant is Locked
Test Case 2 Passed

Running Test Case 3: Unlocking a Node Locked by Another User
Test Case 3 Passed

Running Test Case 4: Unlocking a Node That Is Not Locked
Test Case 4 Passed

Running Test Case 5: Upgrade Lock on an Already Locked Node
Test Case 5 Passed

Running Test Case 6: Upgrade Lock with No Locked Descendants
Test Case 6 Passed

Running Test Case 7: Upgrade Lock When Not All Descendants Are Locked by the Same User
Test Case 7 Passed

Running Test Case 8: Successful Lock Operation with No Conflicts
Test Case 8 Passed

Running Test Case 9: Unlocking a Node That Has Been Upgraded
Test Case 9 Passed

Running Test Case 10: Maximum Nodes with Upgrade Lock
Test Case 10 Passed

Running Test Case 11: Unlocking After Upgrade Lock
Test Case 11 Passed

Running Test Case 12: Locking an Already Locked Node
Test Case 12 Passed

Running Test Case 13: Re-locking an Unlocked Node
Test Case 13 Passed

Running Test Case 14: Locking Sibling Nodes
Test Case 14 Passed

Running Test Case 15: Complex Upgrade and Lock Scenario
Test Case 15 Passed

Running Test Case 1: Locking a Node When an Ancestor is Locked
Test Case 16 Passed

Running Test Case 2: Locking a Node When a Descendant is Locked
Test Case 17 Passed

Running Test Case 3: Unlocking a Node Locked by Another User
Test Case 18 Passed

Running Test Case 4: Unlocking a Node That Is Not Locked
Test Case 19 Passed

Running Test Case 5: Upgrade Lock on an Already Locked Node
Test Case 20 Passed

Running Test Case 6: Upgrade Lock with No Locked Descendants
Test Case 21 Passed

Running Test Case 7: Upgrade Lock When Not All Descendants Are Locked by the Same User
Test Case 22 Passed

Running Test Case 8: Successful Lock Operation with No Conflicts
Test Case 23 Passed

Running Test Case 9: Unlocking a Node That Has Been Upgraded
Test Case 24 Passed

Running Test Case 10: Maximum Nodes and Upgrade Lock
Test Case 25 Failed
Expected Output:
true
true
true
true
true
true
true
true
true
false
Actual Output:
Error: not enough values to unpack (expected 3, got 0)

Running Test Case 11: Unlocking After Upgrade Lock
Test Case 26 Passed

Running Test Case 12: Locking an Already Locked Node
Test Case 27 Passed

Running Test Case 13: Re-locking an Unlocked Node
Test Case 28 Passed

Running Test Case 14: Locking Sibling Nodes
Test Case 29 Passed

Running Test Case 15: Complex Upgrade and Lock Scenario
Test Case 30 Passed

Running Test Case 16: Lock, Unlock, and Relock Sequence
Test Case 31 Failed
Expected Output:
true
true
true
false
true
false
Actual Output:
true
true
true
false
false
false

Running Test Case 17: Locking with Maximum m (m=30)
Test Case 32 Passed

Running Test Case 18: Upgrade Lock with Mixed Users in Descendants
Test Case 33 Passed

Running Test Case 19: Repeated Lock and Unlock on the Same Node
Test Case 34 Passed

Running Test Case 20: Locking Nodes with the Same User
Test Case 35 Passed

Running Test Case 21: Attempt to Lock Ancestor After Locking Descendant
Test Case 36 Passed

Running Test Case 22: Attempt to Lock Descendant After Locking Ancestor
Test Case 37 Passed

Running Test Case 23: Unlocking Node Locked with Different User ID
Test Case 38 Passed

Running Test Case 24: Upgrade Lock with No Locked Descendants
Test Case 39 Passed

Running Test Case 25: Locking All Descendants and Then Ancestor
Test Case 40 Passed

Running Test Case 26: Unlocking After Upgrading Lock
Test Case 41 Failed
Expected Output:
true
true
true
false
true
Actual Output:
true
true
true
false

Running Test Case 27: Upgrade Lock by Different User
Test Case 42 Passed

Running Test Case 28: Locking Nodes After Unlocking Ancestor
Test Case 43 Passed

Running Test Case 29: Locking and Unlocking with Multiple Users
Test Case 44 Passed

Running Test Case 30: Edge Case with m=1 (Linked List Tree)
Test Case 45 Passed

Some test cases failed. Please review your code.
(base) asvinir@Asvinis-MacBook-Air learnDsa % 
"""
"""
# **Locking The Tree of Space**

You have a world map represented as an M-Ary tree (sample tree below)  

<aside>

<img src="./images/asterisk_green.svg" alt="asterisk_green.svg" width="15px" /> In graph theory, an m-ary tree (for nonnegative integers m) (also known as n-ary, k-ary or k-way tree) is an arborescence (or an ordered tree) in which each node has no more than m children. A binary tree is the special case where m = 2, and a ternary tree is another case with m = 3 that limits its children to three.

<img src="./images/asterisk_green.svg" alt="asterisk_green.svg" width="15px" /> In graph theory, an arborescence is a directed graph in which, for a vertex u (called the root) and any other vertex v, there is exactly one directed path from u to v. A graph is a collection of vertices (also known as nodes) and edges that connect these vertices. A tree is a special type of graph that is connected and acyclic, meaning that there are no cycles in the graph. In a tree, there is a unique path between any two vertices, and there is a single vertex called the root that is used as the starting point for traversing the tree. 

</aside>

![Sample Tree](./images/Sample%20Tree.png)

You need to define three operations on it:

```cpp
1. lock(X, uid)
2. unlock(X, uid)
3. upgradeLock(X, uid)
```

where `X` the name of a node in the tree (that would be unique) and `uid` is the user who is performing the operation.  
**Input format**: x is country name (string) and uid is user number (number).

**Here are the definitions for the operations:**

>**`lock(x, uid)`**  
Lock takes an exclusive access on the subtree rooted at `X`. It is formally defined like this: Once `lock(x, uid)` succeeds, then:  
    <li>`lock(A, anyUserid)` should fail (returns false), where `A` is a descendent of `X`,</li>
    <li>`lock(B, anyUserld)` should fail (returns false), where `X` is a descendent of `B`,</li>
    <li>Lock operation cannot be performed on a node which is already locked i.e. `lock(x, anyUserld)` should fail (returns false).</li>  
    <aside>
    <img src="./images/asterisk_green.svg" alt="asterisk_green.svg" width="15px" /> Exclusive access means that only one user can lock a node and its descendants at a time, and no other user can lock any node that is related to the locked node by ancestry or descent. This ensures that there is no conflict or interference between different users who want to perform operations on the tree.
    </aside> 

>**`unlock(X, uid)`**  
Unlock reverts what was done by the lock operation. It can only be called on same node on which user `uid` had called a Lock on before. Returns true if it is successful.

>**`upgradeLock(x, uid)`**  
It helps the user `uid` upgrade their lock to an ancestor node. It is only possible if the node `X` already has locked descendants and all of them are only locked by the same user `uid`. Upgrade should fail if there is any node which is descendant of X that is locked by a different user. Successful Upgrade will 'lock' the node. `upgradeLock` call shouldn't violate the consistency model that Lock/Unlock function requires.

**Notes**

1. The number of nodes in the tree `N` is very large. So, optimize the time complexity for the above algorithms.
2. The below section contains the input format.
    - The first line contains the **number** of Nodes in the tree (`N`).
    - The second line contains **number** of children per node (value `m` in m-ary Tree).
    - The third line contains **number** of queries (`Q`).
    - Next **`N`** lines contains the **`NodeName`** (string) in the m-Ary Tree.
    - Next **`Q`** lines contains queries which are in format: 
    **`Operation Type` `NodeName` `Userld`**
    - **Operation Type**
        
        `1` for lock  
        `2` for unlock  
        `3` for upgradeLock
        
    - **`NodeName`** - Name of any node (unique) in m-Ary Tree.
    - **`Userld`** - Integer value representing a unique user.

**Example input**

```cpp
7
2
3
World
Asia
Africa
China
India
South Africa
Egypt
1 China 9
2 India 9
3 Asia 9
```

With the above input you represent a 2-ary tree with 7 nodes as follows:

```
                 World
            /             \
        Asia               Africa
      /      \          /         \
China    India    South Africa   Egypt
```

**Additional Notes**

1. Here `1 China 3` indicates the following '`Operation Type` `NodeName` `Userld`'.
2. The tree is always fully balanced.
3. Constraints on the inputs are as follows:  
1 < **N** < 5 * 10^5  
1 < **m** < 30  
1 < **Q** <5 * 10^5  
1 < length of **NodeName** < 20
4. Optimize the time complexity:
    - Lock - O(logmN)
    - Unlock - O(logmN)
    - UpgradeLock - O(numberOfLockedNodes * logmN)
5. Lock operation on already locked node should fail.
6. Once Upgrade lock(X, uid) succeeds on X. It is equivalent to X being locked by uid. So, Lock(A/B, anyuser) should fail as per the definition of Lock and Unlock(X, uid) should also work.
7. Upgrade lock operation on a node having no locked descendants should fail and upgrade lock on already locked node should also fail.

**Example input**

```cpp
7
2
5
World
Asia
Africa
China
India
SouthAfrica
Egypt
1 China 9
1 India 9
3 Asia 9
2 India 9
2 Asia 9
```

**Example input**

```cpp
true
true
true
false
true
```

Query 1: `1 China 9` ⇒ This operation is success as initially China is unlocked. 

Query 2: `1 India 9` ⇒ This should be success as none of ancestors and descendants of India are locked.

Query 3: `3 Asia 9` ⇒ This also should be success as upgrade operation is done by same user who has locked descendants.

Query 4: `2 India 9` ⇒ This should fail as the India is now not locked 

Query 5: `2 Asia 9` ⇒ This should be success as Asia was earlier (refer Query 3) locked by user 9.
"""
please correct my code logic 
import sys
import io
import contextlib

# The code to be tested (your solution)
code_to_test = '''
from collections import defaultdict, deque
import sys

class Node:
    def __init__(self, name):
        self.name = name
        self.user_id = None                 # ID of the user who locked the node
        self.parent = None                  # Parent node
        self.children = []                  # List of child nodes
        self.is_locked = False              # Lock status of the node
        self.locked_descendant_count = 0    # Number of locked descendants
        self.dfs_in = 0                     # Entry time in DFS traversal
        self.dfs_out = 0                    # Exit time in DFS traversal

class Tree:
    def __init__(self, n, m, name_list):
        self.node_list = []
        self.node_map = {}  # Map from node name to Node object
        self.time = 0       # Time counter for DFS traversal

        # Create nodes and map their names
        for name in name_list:
            node = Node(name)
            self.node_list.append(node)
            self.node_map[name] = node

        # Build the tree
        for i in range(n):
            parent = self.node_list[i]
            first_child_index = m * i + 1
            for j in range(m):
                child_index = first_child_index + j
                if child_index < n:
                    child = self.node_list[child_index]
                    parent.children.append(child)
                    child.parent = parent
                else:
                    break

        self.root = self.node_list[0]
        self.user_locked_nodes = defaultdict(set)  # Tracks nodes locked by each user
        self.locked_nodes = set()                 # Set of all currently locked nodes

        # Assign DFS in and out times
        self.assign_dfs_times(self.root)

    def assign_dfs_times(self, node):
        stack = []
        stack.append((node, False))
        while stack:
            current_node, visited = stack.pop()
            if not visited:
                # Pre-order position
                self.time += 1
                current_node.dfs_in = self.time
                stack.append((current_node, True))
                for child in reversed(current_node.children):
                    stack.append((child, False))
            else:
                # Post-order position
                self.time += 1
                current_node.dfs_out = self.time

    def is_ancestor_locked(self, node):
        current = node.parent
        while current:
            if current.is_locked:
                return True
            current = current.parent
        return False

    def is_descendant(self, u, v):
        # Returns True if node u is a descendant of node v
        return v.dfs_in < u.dfs_in < u.dfs_out < v.dfs_out

    def lock(self, node, user_id):
        # If the node is already locked, return False
        if node.is_locked:
            return False

        # If any ancestors are locked, cannot lock this node
        if self.is_ancestor_locked(node):
            return False

        # If any descendants are locked, cannot lock this node
        if node.locked_descendant_count > 0:
            return False

        # Lock the node
        node.is_locked = True
        node.user_id = user_id
        self.user_locked_nodes[user_id].add(node)
        self.locked_nodes.add(node)

        # Update the locked_descendant_count for ancestors
        parent = node.parent
        while parent:
            parent.locked_descendant_count += 1
            parent = parent.parent

        return True

    def unlock(self, node, user_id):
        # The node must be locked and the user_id must match
        if not node.is_locked or node.user_id != user_id:
            return False

        # Unlock the node
        node.is_locked = False
        node.user_id = None
        self.user_locked_nodes[user_id].remove(node)
        self.locked_nodes.remove(node)

        # Update the locked_descendant_count for ancestors
        parent = node.parent
        while parent:
            parent.locked_descendant_count -= 1
            parent = parent.parent

        return True

    def upgrade(self, node, user_id):
        # The node must not be locked
        if node.is_locked:
            return False

        # If any ancestors are locked, cannot upgrade this node
        if self.is_ancestor_locked(node):
            return False

        # The node must have at least one locked descendant
        if node.locked_descendant_count == 0:
            return False

        # Check if any locked descendants are locked by other users
        for locked_node in self.locked_nodes:
            if self.is_descendant(locked_node, node) and locked_node.user_id != user_id:
                return False

        # Collect all locked descendants locked by the user
        locked_descendants = []
        for locked_node in self.user_locked_nodes[user_id]:
            if self.is_descendant(locked_node, node):
                locked_descendants.append(locked_node)

        if not locked_descendants:
            return False

        # Unlock all locked descendants
        for descendant in locked_descendants:
            descendant.is_locked = False
            descendant.user_id = None
            self.user_locked_nodes[user_id].remove(descendant)
            self.locked_nodes.remove(descendant)

            # Update the locked_descendant_count for ancestors
            parent = descendant.parent
            while parent:
                parent.locked_descendant_count -= 1
                parent = parent.parent

        # Lock the current node
        node.is_locked = True
        node.user_id = user_id
        self.user_locked_nodes[user_id].add(node)
        self.locked_nodes.add(node)

        # Update the locked_descendant_count for ancestors
        parent = node.parent
        while parent:
            parent.locked_descendant_count += 1
            parent = parent.parent

        return True

    def process_query(self, operation_type, node_name, user_id):
        node = self.node_map[node_name]
        if operation_type == "1":
            return self.lock(node, user_id)
        elif operation_type == "2":
            return self.unlock(node, user_id)
        elif operation_type == "3":
            return self.upgrade(node, user_id)
        else:
            return False  # Invalid operation

def main():
    sys.setrecursionlimit(1 << 25)  # Increase recursion limit if necessary

    # Read input
    n = int(sys.stdin.readline())
    m = int(sys.stdin.readline())
    q = int(sys.stdin.readline())

    name_list = [sys.stdin.readline().strip() for _ in range(n)]
    tree = Tree(n, m, name_list)

    # Process queries
    results = []
    for _ in range(q):
        query = sys.stdin.readline().strip().split()
        operation_type, node_name, user_id = query
        user_id = int(user_id)
        result = tree.process_query(operation_type, node_name, user_id)
        results.append('true' if result else 'false')

    for res in results:
        print(res)


main()


'''

# List of test cases
test_cases = [
    {
        "description": "Test Case 1: Locking a Node When an Ancestor is Locked",
        "input": """7
2
2
World
Asia
Africa
China
India
SouthAfrica
Egypt
1 Asia 1
1 China 2
""",
        "expected_output": """true
false
"""
    },
    {
        "description": "Test Case 2: Locking a Node When a Descendant is Locked",
        "input": """7
2
2
World
Asia
Africa
China
India
SouthAfrica
Egypt
1 India 1
1 Asia 2
""",
        "expected_output": """true
false
"""
    },
    {
        "description": "Test Case 3: Unlocking a Node Locked by Another User",
        "input": """3
2
2
Root
Child1
Child2
1 Child1 1
2 Child1 2
""",
        "expected_output": """true
false
"""
    },
    {
        "description": "Test Case 4: Unlocking a Node That Is Not Locked",
        "input": """3
2
1
Root
Child1
Child2
2 Child1 1
""",
        "expected_output": """false
"""
    },
    {
        "description": "Test Case 5: Upgrade Lock on an Already Locked Node",
        "input": """3
2
2
Root
Child1
Child2
1 Root 1
3 Root 1
""",
        "expected_output": """true
false
"""
    },
    {
        "description": "Test Case 6: Upgrade Lock with No Locked Descendants",
        "input": """3
2
1
Root
Child1
Child2
3 Root 1
""",
        "expected_output": """false
"""
    },
    {
        "description": "Test Case 7: Upgrade Lock When Not All Descendants Are Locked by the Same User",
        "input": """7
2
3
World
Asia
Africa
China
India
SouthAfrica
Egypt
1 China 1
1 India 2
3 Asia 1
""",
        "expected_output": """true
true
false
"""
    },
    {
        "description": "Test Case 8: Successful Lock Operation with No Conflicts",
        "input": """3
2
1
Root
Child1
Child2
1 Child1 1
""",
        "expected_output": """true
"""
    },
    {
        "description": "Test Case 9: Unlocking a Node That Has Been Upgraded",
        "input": """7
2
5
World
Asia
Africa
China
India
SouthAfrica
Egypt
1 China 9
1 India 9
3 Asia 9
2 India 9
2 Asia 9
""",
        "expected_output": """true
true
true
false
true
"""
    },
    {
        "description": "Test Case 10: Maximum Nodes with Upgrade Lock",
        "input": """15
2
8
Root
A
B
C
D
E
F
G
H
I
J
K
L
M
N
1 H 1
1 I 1
1 J 1
1 K 1
1 L 1
1 M 1
1 N 1
3 Root 1
""",
        "expected_output": """true
true
true
true
true
true
true
true
"""
    },
    {
        "description": "Test Case 11: Unlocking After Upgrade Lock",
        "input": """7
2
5
World
Asia
Africa
China
India
SouthAfrica
Egypt
1 China 9
1 India 9
3 Asia 9
2 China 9
2 Asia 9
""",
        "expected_output": """true
true
true
false
true
"""
    },
    {
        "description": "Test Case 12: Locking an Already Locked Node",
        "input": """3
2
2
Root
Child1
Child2
1 Child1 1
1 Child1 2
""",
        "expected_output": """true
false
"""
    },
    {
        "description": "Test Case 13: Re-locking an Unlocked Node",
        "input": """3
2
3
Root
Child1
Child2
1 Child1 1
2 Child1 1
1 Child1 2
""",
        "expected_output": """true
true
true
"""
    },
    {
        "description": "Test Case 14: Locking Sibling Nodes",
        "input": """3
2
2
Root
Child1
Child2
1 Child1 1
1 Child2 2
""",
        "expected_output": """true
true
"""
    },
    {
        "description": "Test Case 15: Complex Upgrade and Lock Scenario",
        "input": """9
3
10
Root
A
B
C
D
E
F
G
H
1 D 1
1 E 1
1 F 2
3 B 1
1 G 1
3 Root 1
2 Root 1
1 H 2
1 A 2
3 Root 2
""",
        "expected_output": """true
true
true
false
true
false
false
true
false
false
"""
    },
    {
        "description": "Test Case 1: Locking a Node When an Ancestor is Locked",
        "input": """7
2
2
World
Asia
Africa
China
India
SouthAfrica
Egypt
1 Asia 1
1 China 2
""",
        "expected_output": """true
false
"""
    },
    {
        "description": "Test Case 2: Locking a Node When a Descendant is Locked",
        "input": """7
2
2
World
Asia
Africa
China
India
SouthAfrica
Egypt
1 India 1
1 Asia 2
""",
        "expected_output": """true
false
"""
    },
    {
        "description": "Test Case 3: Unlocking a Node Locked by Another User",
        "input": """3
2
2
Root
Child1
Child2
1 Child1 1
2 Child1 2
""",
        "expected_output": """true
false
"""
    },
    {
        "description": "Test Case 4: Unlocking a Node That Is Not Locked",
        "input": """3
2
1
Root
Child1
Child2
2 Child1 1
""",
        "expected_output": """false
"""
    },
    {
        "description": "Test Case 5: Upgrade Lock on an Already Locked Node",
        "input": """3
2
2
Root
Child1
Child2
1 Root 1
3 Root 1
""",
        "expected_output": """true
false
"""
    },
    {
        "description": "Test Case 6: Upgrade Lock with No Locked Descendants",
        "input": """3
2
1
Root
Child1
Child2
3 Root 1
""",
        "expected_output": """false
"""
    },
    {
        "description": "Test Case 7: Upgrade Lock When Not All Descendants Are Locked by the Same User",
        "input": """7
2
3
World
Asia
Africa
China
India
SouthAfrica
Egypt
1 China 1
1 India 2
3 Asia 1
""",
        "expected_output": """true
true
false
"""
    },
    {
        "description": "Test Case 8: Successful Lock Operation with No Conflicts",
        "input": """3
2
1
Root
Child1
Child2
1 Child1 1
""",
        "expected_output": """true
"""
    },
    {
        "description": "Test Case 9: Unlocking a Node That Has Been Upgraded",
        "input": """7
2
5
World
Asia
Africa
China
India
SouthAfrica
Egypt
1 China 9
1 India 9
3 Asia 9
2 India 9
2 Asia 9
""",
        "expected_output": """true
true
true
false
true
"""
    },
    {
        "description": "Test Case 10: Maximum Nodes and Upgrade Lock",
        "input": """31
2
16
Root
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
AA
AB
AC
AD
1 Z 1
1 AA 1
1 AB 1
1 AC 1
1 AD 1
3 Root 1
1 E 2
1 F 2
1 G 2
3 Root 2
""",
        "expected_output": """true
true
true
true
true
true
true
true
true
false
"""
    },
    {
        "description": "Test Case 11: Unlocking After Upgrade Lock",
        "input": """7
2
5
World
Asia
Africa
China
India
SouthAfrica
Egypt
1 China 9
1 India 9
3 Asia 9
2 China 9
2 Asia 9
""",
        "expected_output": """true
true
true
false
true
"""
    },
    {
        "description": "Test Case 12: Locking an Already Locked Node",
        "input": """3
2
2
Root
Child1
Child2
1 Child1 1
1 Child1 2
""",
        "expected_output": """true
false
"""
    },
    {
        "description": "Test Case 13: Re-locking an Unlocked Node",
        "input": """3
2
3
Root
Child1
Child2
1 Child1 1
2 Child1 1
1 Child1 2
""",
        "expected_output": """true
true
true
"""
    },
    {
        "description": "Test Case 14: Locking Sibling Nodes",
        "input": """3
2
2
Root
Child1
Child2
1 Child1 1
1 Child2 2
""",
        "expected_output": """true
true
"""
    },
    {
        "description": "Test Case 15: Complex Upgrade and Lock Scenario",
        "input": """9
3
10
Root
A
B
C
D
E
F
G
H
1 D 1
1 E 1
1 F 2
3 B 1
1 G 1
3 Root 1
2 Root 1
1 H 2
1 A 2
3 Root 2
""",
        "expected_output": """true
true
true
false
true
false
false
true
false
false
"""
    },
    {
        "description": "Test Case 16: Lock, Unlock, and Relock Sequence",
        "input": """5
2
6
Root
Child1
Child2
GrandChild1
GrandChild2
1 GrandChild1 1
2 GrandChild1 1
1 GrandChild1 2
1 Root 3
1 Child1 4
3 Root 3
""",
        "expected_output": """true
true
true
false
true
false
"""
    },
    {
        "description": "Test Case 17: Locking with Maximum m (m=30)",
        "input": """31
30
2
Root
Node1
Node2
Node3
Node4
Node5
Node6
Node7
Node8
Node9
Node10
Node11
Node12
Node13
Node14
Node15
Node16
Node17
Node18
Node19
Node20
Node21
Node22
Node23
Node24
Node25
Node26
Node27
Node28
Node29
Node30
1 Node15 1
3 Root 1
""",
        "expected_output": """true
true
"""
    },
    {
        "description": "Test Case 18: Upgrade Lock with Mixed Users in Descendants",
        "input": """7
2
4
Root
Child1
Child2
GrandChild1
GrandChild2
GrandChild3
GrandChild4
1 GrandChild1 1
1 GrandChild2 2
3 Child1 1
3 Root 1
""",
        "expected_output": """true
true
false
false
"""
    },
    {
        "description": "Test Case 19: Repeated Lock and Unlock on the Same Node",
        "input": """3
2
5
Root
Child1
Child2
1 Child1 1
2 Child1 1
1 Child1 1
2 Child1 1
1 Child1 1
""",
        "expected_output": """true
true
true
true
true
"""
    },
    {
        "description": "Test Case 20: Locking Nodes with the Same User",
        "input": """5
2
3
Root
Child1
Child2
GrandChild1
GrandChild2
1 GrandChild1 1
1 GrandChild2 1
1 Root 1
""",
        "expected_output": """true
true
false
"""
    },
    {
        "description": "Test Case 21: Attempt to Lock Ancestor After Locking Descendant",
        "input": """3
2
2
Root
Child1
Child2
1 Child1 1
1 Root 1
""",
        "expected_output": """true
false
"""
    },
    {
        "description": "Test Case 22: Attempt to Lock Descendant After Locking Ancestor",
        "input": """3
2
2
Root
Child1
Child2
1 Root 1
1 Child1 1
""",
        "expected_output": """true
false
"""
    },
    {
        "description": "Test Case 23: Unlocking Node Locked with Different User ID",
        "input": """3
2
2
Root
Child1
Child2
1 Child1 1
2 Child1 2
""",
        "expected_output": """true
false
"""
    },
    {
        "description": "Test Case 24: Upgrade Lock with No Locked Descendants",
        "input": """3
2
1
Root
Child1
Child2
3 Child1 1
""",
        "expected_output": """false
"""
    },
    {
        "description": "Test Case 25: Locking All Descendants and Then Ancestor",
        "input": """7
2
5
Root
Child1
Child2
GrandChild1
GrandChild2
GrandChild3
GrandChild4
1 GrandChild1 1
1 GrandChild2 1
1 GrandChild3 1
1 GrandChild4 1
3 Root 1
""",
        "expected_output": """true
true
true
true
true
"""
    },
    {
        "description": "Test Case 26: Unlocking After Upgrading Lock",
        "input": """3
2
4
Root
Child1
Child2
1 Child1 1
1 Child2 1
3 Root 1
2 Child1 1
2 Root 1
""",
        "expected_output": """true
true
true
false
true
"""
    },
    {
        "description": "Test Case 27: Upgrade Lock by Different User",
        "input": """3
2
3
Root
Child1
Child2
1 Child1 1
1 Child2 1
3 Root 2
""",
        "expected_output": """true
true
false
"""
    },
    {
        "description": "Test Case 28: Locking Nodes After Unlocking Ancestor",
        "input": """7
2
5
Root
Child1
Child2
GrandChild1
GrandChild2
GrandChild3
GrandChild4
1 Root 1
2 Root 1
1 GrandChild1 2
1 GrandChild2 2
1 Child1 2
""",
        "expected_output": """true
true
true
true
false
"""
    },
    {
        "description": "Test Case 29: Locking and Unlocking with Multiple Users",
        "input": """5
2
6
Root
Child1
Child2
GrandChild1
GrandChild2
1 GrandChild1 1
1 GrandChild2 2
1 Child1 3
2 GrandChild1 1
1 Child1 3
3 Root 1
""",
        "expected_output": """true
true
false
true
false
false
"""
    },
    {
        "description": "Test Case 30: Edge Case with m=1 (Linked List Tree)",
        "input": """5
1
5
Root
Node1
Node2
Node3
Node4
1 Node4 1
1 Node2 2
2 Node4 1
1 Node2 2
1 Root 3
""",
        "expected_output": """true
false
true
true
false
"""
    },

]

# Function to run the test case
def run_test_case(code, test_input):
    # Redirect stdin and stdout
    old_stdin = sys.stdin
    old_stdout = sys.stdout
    sys.stdin = io.StringIO(test_input)
    sys.stdout = io.StringIO()
    namespace = {}
    
    try:
        exec(code, namespace)
        output = sys.stdout.getvalue()
    except Exception as e:
        output = f"Error: {e}"
    finally:
        # Restore stdin and stdout
        sys.stdin = old_stdin
        sys.stdout = old_stdout
    
    return output.strip()

# Main testing function
def test_code_on_test_cases():
    all_passed = True
    for idx, test in enumerate(test_cases, 1):
        print(f"Running {test['description']}")
        output = run_test_case(code_to_test, test['input'])
        expected_output = test['expected_output'].strip()
        if output == expected_output:
            print(f"Test Case {idx} Passed\n")
        else:
            print(f"Test Case {idx} Failed")
            print("Expected Output:")
            print(expected_output)
            print("Actual Output:")
            print(output)
            print()
            all_passed = False
    if all_passed:
        print("All test cases passed!")
    else:
        print("Some test cases failed. Please review your code.")

# Run the tests
test_code_on_test_cases()