from collections import deque
def nearest_meeting_cell(n, edges, c1, c2):
def bfs(start):
"""Performs BFS from the start cell and returns a dictionary of distances."""
distances = {}
queue = deque([(start, 0)])
visited = set()
while queue:
node, dist = queue.popleft()
if node in visited:
continue
visited.add(node)
distances[node] = dist
# Move to the next node if it exists and hasn't been visited
next_node = edges[node]
if next_node != -1 and next_node not in visited:
queue.append((next_node, dist + 1))
return distances
# Get reachable distances from both C1 and C2
dist_from_c1 = bfs(c1)
dist_from_c2 = bfs(c2)
# Find common cells that are reachable from both
common_cells = set(dist_from_c1.keys()) & set(dist_from_c2.keys())
if not common_cells:
return -1 # No meeting cell
# Find the nearest meeting cell
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 reading
n = int(input()) # Number of cells
edges = list(map(int, input().split())) # Edges array
c1, c2 = map(int, input().split()) # Two cells to check
# Output the nearest meeting cell
print(nearest_meeting_cell(n, edges, c1, c2))
ZnJvbSBjb2xsZWN0aW9ucyBpbXBvcnQgZGVxdWUKCmRlZiBuZWFyZXN0X21lZXRpbmdfY2VsbChuLCBlZGdlcywgYzEsIGMyKToKICAgIGRlZiBiZnMoc3RhcnQpOgogICAgICAgICIiIlBlcmZvcm1zIEJGUyBmcm9tIHRoZSBzdGFydCBjZWxsIGFuZCByZXR1cm5zIGEgZGljdGlvbmFyeSBvZiBkaXN0YW5jZXMuIiIiCiAgICAgICAgZGlzdGFuY2VzID0ge30KICAgICAgICBxdWV1ZSA9IGRlcXVlKFsoc3RhcnQsIDApXSkKICAgICAgICB2aXNpdGVkID0gc2V0KCkKICAgICAgICAKICAgICAgICB3aGlsZSBxdWV1ZToKICAgICAgICAgICAgbm9kZSwgZGlzdCA9IHF1ZXVlLnBvcGxlZnQoKQogICAgICAgICAgICBpZiBub2RlIGluIHZpc2l0ZWQ6CiAgICAgICAgICAgICAgICBjb250aW51ZQogICAgIC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