#C542. Detecting Cycles in a Directed Graph

    ID: 49067 Type: Default 1000ms 256MiB

Detecting Cycles in a Directed Graph

Detecting Cycles in a Directed Graph

You are given a directed graph with n nodes and m edges. The graph is represented by a list of directed edges. Your task is to determine whether the graph contains any cycle.

A cycle in a directed graph is defined as a sequence of vertices \(v_1, v_2, \dots, v_k\) such that there is an edge from \(v_i\) to \(v_{i+1}\) for \(1 \leq i < k\) and an edge from \(v_k\) back to \(v_1\). Formally, a cycle exists if and only if there exists a sequence of vertices satisfying:

\[ v_1 \to v_2 \to \cdots \to v_k \to v_1, \]

Output "Yes" if a cycle exists in the graph; otherwise, output "No".

inputFormat

The first line contains two integers, n and m, separated by a space, representing the number of nodes and the number of edges respectively. The following m lines each contain two integers u and v, indicating a directed edge from node u to node v.

outputFormat

Output a single line containing "Yes" if the graph contains a cycle, or "No" if it does not.## sample

4 4
1 2
2 3
3 4
4 2
Yes

</p>