Endless Road

mediumGraph

There are $$$n$$$ cities connected by $$$m$$$ one-way roads (directed edges). You want to determine whether it is possible to start your journey from some city, walk along the roads, and return to the same city by following the direction of the roads.

If such a cycle is possible, print YES. Otherwise, print NO.

Input Format:

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5$$$, $$$0 \le m < \min(n \cdot (n - 1),\ 2 \cdot 10^5)$$$) — the number of cities and one-way roads.

Each of the next $$$m$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$), indicating a one-way road from city $$$u$$$ to city $$$v$$$.

Output Format:

Print YES if there exists a cycle (i.e., you can return to the same city); otherwise, print NO.

Examples:

Example 1:

Input:

3 3
1 2
2 3
3 1

Output:

YES

Example 2:

Input:

4 3
1 2
2 3
3 4

Output:

NO

Note:

In testcase 1, there is a cycle: $$$1 \rightarrow 2 \rightarrow 3 \rightarrow 1$$$, so the output is YES.

In testcase 2, there is no cycle: $$$1 \rightarrow 2 \rightarrow 3 \rightarrow 4$$$, so the output is NO.

Code

Loading Editor...