Practice arena
C++17·2 s·128 MB
GraphsIntermediate

Dependency cycle

Determine whether a directed graph contains a cycle. Vertices are numbered 0 through n-1.

Input

  • The first line contains T.
  • Each case starts with n and m, followed by m directed edges u v.

Output

Print YES when a cycle exists; otherwise print NO.

Technique

three-colour DFS

Target

O(V + E)

Constraints & sample
  • 1 ≤ n ≤ 200,000
  • 0 ≤ m ≤ 300,000

Sample input

3
4 4
0 1
1 2
2 3
3 1
4 3
0 1
1 2
2 3
1 1
0 0

Expected output

YES
NO
YES
Review the concept

Before you submit

  • Test the smallest valid input and one awkward edge case.
  • Keep the solution within O(V + E).
  • Match spacing and line breaks exactly before checking 8 hidden cases.
main.cpp
Draft saved locally · 444 / 30,000
Ln 1, Col 1Spaces: 4UTF-8LFC++17

Visible testcases

Editable and stored only in this browser. Hidden judge cases never change.

Checking your session…

Run checks Sample · Submit checks 8 hidden cases

Run the sample first, then send your solution through 8 hidden cases.

Code runs in an isolated Judge0 environment. Drafts and custom visible cases stay on this device; submission metadata and progress sync to MongoDB.