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}")
