DOJ logoDOJ
Problems
Recently added problemsSaved problems
CategoriesDLCContestsGroupsTeamsBoard
Ranking
Solved Problem RankingStreak rankingDOJ Power ranking
Status
Call for TasksLoginRegister
DOJ logoDOJ

Community online judge with OI-style subtask scoring, Elo ratings, and Discord-backed certification.

Problems
ProblemsCategories
Community
ContestsRankingBoardNoticesHost an external contestGuide
Account
LoginRegisterJudge Status
Policy
Terms of ServiceDLC RulesPrivacyAPI documentationLanguage runtimesContest rank rewardsRating and performance
© 2026 DOJ
All rights reserved
Editorial

I Want to Cycle.

Back to problem

Editorial

The cycle-related information can be handled using strongly connected components.

First, decompose the directed graph into strongly connected components. Any strongly connected component of size at least 222 contains a cycle. Since the input contains no self-loops, a strongly connected component of size 111 does not contain a cycle.

If each strongly connected component is contracted into one vertex, the resulting graph is a DAG. An original vertex can visit a cycle if and only if its strongly connected component can reach a strongly connected component that contains a cycle.

Therefore, we can solve the problem as follows.

  • Find all strongly connected components of the graph.
  • Mark every strongly connected component of size at least 222 as a component containing a cycle.
  • Build the reversed edges of the strongly connected component DAG.
  • Starting from all components containing a cycle, run DFS or BFS along the reversed edges.

Every visited strongly connected component can reach a component containing a cycle in the original direction. Hence, the vertices belonging to unvisited components are exactly the vertices counted in the answer.

The time complexity is O(N+M)O(N+M)O(N+M), and the memory complexity is O(N+M)O(N+M)O(N+M).