from collections import deque
def nearest_meeting_cell(n, edges, c1, c2):
def bfs(start):
"""BFS to calculate shortest distance from the start node."""
distances = {}
queue = deque([(start, 0)]) # (current node, current distance)
visited = set()
while queue:
node, dist = queue.popleft()
if node in visited: # Skip already visited nodes
continue
visited.add(node)
distances[node] = dist
# Traverse to the next node if it exists and is unvisited
next_node = edges[node]
if next_node != -1 and next_node not in visited:
queue.append((next_node, dist + 1))
return distances
# Step 1: Get distances from C1 and C2
dist_from_c1 = bfs(c1)
dist_from_c2 = bfs(c2)
# Step 2: Find common cells reachable from both C1 and C2
common_cells = set(dist_from_c1.keys()) & set(dist_from_c2.keys())
if not common_cells:
return -1 # No common meeting cell
# Step 3: Find the nearest meeting cell with the smallest max distance
nearest_cell = -1
min_distance = float('inf')
for cell in common_cells:
total_distance = max(dist_from_c1[cell], dist_from_c2[cell])
if total_distance < min_distance:
min_distance = total_distance
nearest_cell = cell
return nearest_cell
# Input Parsing
if __name__ == "__main__":
n = int(input("Enter the number of cells (N): ")) # Number of cells
edges = list(map(int, input("Enter the edges array: ").split())) # Edges array
c1, c2 = map(int, input("Enter the two cells (C1 and C2): ").split()) # Query cells
# Output the nearest meeting cell
result = nearest_meeting_cell(n, edges, c1, c2)
print(f"Nearest Meeting Cell: {result}")
ZnJvbSBjb2xsZWN0aW9ucyBpbXBvcnQgZGVxdWUKCmRlZiBuZWFyZXN0X21lZXRpbmdfY2VsbChuLCBlZGdlcywgYzEsIGMyKToKICAgIGRlZiBiZnMoc3RhcnQpOgogICAgICAgICIiIkJGUyB0byBjYWxjdWxhdGUgc2hvcnRlc3QgZGlzdGFuY2UgZnJvbSB0aGUgc3RhcnQgbm9kZS4iIiIKICAgICAgICBkaXN0YW5jZXMgPSB7fQogICAgICAgIHF1ZXVlID0gZGVxdWUoWyhzdGFydCwgMCldKSAgIyAoY3VycmVudCBub2RlLCBjdXJyZW50IGRpc3RhbmNlKQogICAgICAgIHZpc2l0ZWQgPSBzZXQoKQogICAgICAgIAogICAgICAgIH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