#C5891. Find the Manager at the k-th Level Above

    ID: 49590 Type: Default 1000ms 256MiB

Find the Manager at the k-th Level Above

Find the Manager at the k-th Level Above

You are given a company hierarchy represented as a tree. Each node in the tree represents an employee, and the direct report relation is given as a pair \( (u, v) \), meaning that employee \( v \) directly reports to employee \( u \). Given an employee \( e \) and an integer \( k \), your task is to find the manager who is \( k \) levels above employee \( e \). If there is no such manager, output -1.

The hierarchy is defined by:

  • \( n \): the number of employees.
  • \( reports \): a list of pairs \( (u, v) \) indicating that employee \( v \) directly reports to employee \( u \).

For example, consider \( n = 7 \) and the following direct reporting relations:

( \begin{aligned} (1, 2),; (1, 3),; (2, 4),; (2, 5),; (3, 6),; (3, 7) \end{aligned} )

Some examples:

  • For \( e = 5 \) and \( k = 2 \), the output is \( 1 \).
  • For \( e = 4 \) and \( k = 1 \), the output is \( 2 \).
  • For \( e = 6 \) and \( k = 3 \), the output is \( -1 \) (no such manager exists).

Note: If \( k = 0 \), you should return \( e \) itself.

inputFormat

The input is read from standard input (stdin) and has the following format:

 n r
 u1 v1
 u2 v2
 ...
 ur vr
 e k

Where:

  • \( n \) is the number of employees.
  • \( r \) is the number of direct reporting relations.
  • Each of the next \( r \) lines contains two integers \( u \) and \( v \) indicating that employee \( v \) reports directly to employee \( u \).
  • Finally, a line contains two integers: \( e \) (the specified employee) and \( k \) (the number of levels above to look for the manager).

outputFormat

Output to standard output (stdout) a single integer, which is the ID of the manager who is \( k \) levels above employee \( e \). If such a manager does not exist, output -1.

## sample
7 6
1 2
1 3
2 4
2 5
3 6
3 7
5 2
1