Directed Cycle Detection
View as PDF
Submit solution
Points:
100
Time limit:
1.0s
PyPy 3
3.0s
Python 3
3.0s
Memory limit:
500M
Problem type
You are given a directed graph with vertices and
edges. Each edge goes from one
vertex to another, and vertices are numbered from
to
.
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 and
: the number of vertices and directed edges.
The next lines each contain two integers
and
, meaning there is a directed edge from
vertex
to vertex
.
Output
Print YES if the graph contains at least one directed cycle. Otherwise, print NO.
Constraints
Example 1
Input
4 3
1 2
2 3
3 4
Output
NO
Explanation
All edges move forward along the chain, so it is impossible to return to a previous vertex.
Example 2
Input
4 4
1 2
2 3
3 1
3 4
Output
YES
Explanation
The edges ,
, and
form a directed cycle.
Comments