All problems

Problem 946

Find Closest Node to Given Two Nodes

Medium · 20 pts · Graph, Breadth-First Search

Problem

A directed graph has N nodes, each with at most one outgoing edge (EDGES[i], or -1). Find the node that can be reached from both NODE1 and NODE2 and minimises the larger of the two distances. If several nodes tie, print the smallest index; if no node is reachable from both, print -1. Walk from each start along the edges, recording the distance to every node it reaches (stop when a node repeats), then compare the two distance arrays.

Input

The first line contains N, NODE1 and NODE2. The second line contains EDGES[0..N-1].

Output

Print the best meeting node, or -1.

Constraints

2 <= N <= 100000; -1 <= EDGES[i] < N; EDGES[i] != i; 0 <= NODE1, NODE2 < N

Example input

4 0 1
2 2 3 -1

Example output

2

Explanation

With EDGES = 2 2 3 -1, NODE1 = 0 and NODE2 = 1, node 2 is one step from both, so the larger distance is 1. Node 3 would need 2 steps, so the answer is 2.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Longest Cycle in a Graph Next: Time Needed to Inform All Employees