#C5103. Cycle Detection in a Labyrinth

    ID: 48716 Type: Default 1000ms 256MiB

Cycle Detection in a Labyrinth

Cycle Detection in a Labyrinth

You are given a labyrinth in the form of a directed graph with n chambers (nodes) and m corridors (directed edges). The corridors connect the chambers in one direction. Given a starting chamber s, your task is to determine whether there exists a path, following the directed corridors, that eventually returns to the starting chamber s. In other words, check if there is a cycle in the graph that includes s.

You can think of the labyrinth as a directed graph \(G(V,E)\), where \(V\) is the set of chambers and \(E\) is the set of corridors. You need to decide if there exists a path \(s \to \cdots \to s\) (with at least one edge) starting from \(s\).

For example, if the labyrinth has 4 chambers and the corridors are:

1 2
2 3
3 4
4 2

starting from chamber 1, there is a cycle (2 → 3 → 4 → 2) reachable from 1 and hence the answer is YES. Otherwise, if no such cycle exists, the answer is NO.

inputFormat

The first line of input contains three integers n, m, and s separated by spaces:

  • n: the number of chambers.
  • m: the number of corridors.
  • s: the starting chamber.

Each of the next m lines contains two integers u and v which indicate that there is a directed corridor from chamber u to chamber v.

Note: The input is provided via standard input (stdin).

outputFormat

Output a single line: YES if there exists a cycle (a path starting and ending at s with at least one edge), and NO otherwise.

Note: The output should be written to standard output (stdout).

## sample
3 2 1
1 2
2 3
NO