I wrote this code and made many changes and submitted it many times but never got an AC even for the smaller case. Please help me find the error. Here’s my code:
import queue
cases = int(input())
class Node:
array = []
def __init__(self, index, parent, weight):
self.index = index
self.parent = parent
self.weight = weight
self.ancestors = []
self.height = 0
Node.array.append(self)
def initialize(self):
if self.parent == None:
self.ancestors = [self.index]
self.height = 0
else:
mother = Node.array[self.parent]
self.ancestors = mother.ancestors[:]
self.ancestors.append(self.index)
self.height = mother.height + 1
for _ in range(cases):
vertices = int(input())
root = Node(0, None, 0)
root.initialize()
to_init = queue.Queue(maxsize=100000)
for vertex in range(vertices - 1):
parent, node, weight = input().split()
parent, node, weight = int(parent) - 1, int(node) - 1, int(weight)
to_init.put(node)
Node(node, parent, weight)
Node.array = sorted(Node.array, key=lambda x: x.index)
while not (to_init.empty()):
index = to_init.get()
Node.array[index].initialize()
queries = int(input())
for query in range(queries):
u, v, limit = input().split()
u, v, limit = int(u) - 1, int(v) - 1, int(limit)
start = Node.array[u]
dest = Node.array[v]
height = min(start.height, dest.height)
xor = 0
for h in range(height - 1, 0, -1):
if start.ancestors[h] == dest.ancestors[h]:
break
if Node.array[start.ancestors[h]].weight <= limit:
xor ^= Node.array[start.ancestors[h]].weight
if Node.array[dest.ancestors[h]].weight <= limit:
xor ^= Node.array[dest.ancestors[h]].weight
for point in start.ancestors[height:] + dest.ancestors[height:]:
weight = Node.array[point].weight
if weight <= limit:
xor ^= weight
print(xor)
Node.array = list()