Directed Cycle Detection
You are given a directed graph with n vertices and m edges. Each edge goes from one vertex to another, and vertices are numbered from 1 to n.
Determine whether the graph contains at least one directed cycle. A directed cycle is a sequence of one or more edges that starts and ends at the same vertex while following edge directions.
Input
The first line contains two integers n and m: the number of vertices and directed edges.
The next m lines each contain two integers a and b, meaning there is a directed edge from vertex a to vertex b.
Output
Print YES if the graph contains at least one directed cycle. Otherwise, print NO.
Constraints
- 1≤n≤200000
- 0≤m≤300000
- 1≤a,b≤n
Example 1
4 3
1 2
2 3
3 4
NO
Explanation
All edges move forward along the chain, so it is impossible to return to a previous vertex.
Example 2
4 4
1 2
2 3
3 1
3 4
YES
Explanation
The edges 1→2, 2→3, and 3→1 form a directed cycle.
Comments0
No comments yet
Be the first to comment.
New comment
Log in to join the discussion.