Yet Another Xinversion !

The problem statement is simple. You are given a rooted tree (1 is the root) and every node has a co…

Click here to read the complete problem statement.


If you need help solving this problem, mention your approach and ask specific questions. Please avoid sharing your code and asking the Community to figure out “what’s wrong”.

I am getting a runtime error and I cannot for the life of me understand why it might be the case. Can someone help me?

class TreeNode: # creating a class to create a node

def __init__(self, value, cost):
    self.value = value
    self.children = []
    self.cost = cost
    self.parent = None

def add_child(self, child): # to add a child node
    self.children.append(child)
    child.parent = self

def add_cost(self, cost): # to do operation 1
    self.cost = cost

def xinverse(self): # to do operation 2
    count = 0
    for child in self.children:
        if child.cost > self.cost: # checks if child is valid
            count += 1
        count += child.xinverse() # repeats the process for the children of the child nodes
    # answer stored in the main variable count
    return count 

taking basic inputs and building the tree from the root node 1 up to the leaf nodes

N, Q = map(int, input().split(’ ‘))
costs = list(map(int, input().split(’ ')))

for n in range(N):
vars()[f’node_{n+1}'] = TreeNode(n+1, costs[n])

for i in range(N-1):
inp_objects = list(map(int, input().split(’ ‘)))
if inp_objects[0] < inp_objects[1]:
vars()[f’node_{inp_objects[0]}’].add_child(vars()[f’node_{inp_objects[1]}‘])
else:
vars()[f’node_{inp_objects[1]}’].add_child(vars()[f’node_{inp_objects[0]}'])

answers =
for q in range(Q):
command = list(map(int, input().split(’ ‘)))
if command[0] == 1:
vars()[f’node_{command[1]}’].add_cost(command[2])
else:
answers.append(str(vars()[f’node_{command[1]}'].xinverse()))

print(‘\n’.join(answers))