Explanation
The theorem being used here is that if one vertex can both reach and be reached by all others, then every vertex in this graph can reach all others.
Let's say is true if you can go from vertex to vertex through a series of edges. Additionally, let's define the directed graph given in the statement as and the reverse of it (where an edge becomes ) as . Then, if for in both and , the answer is "YES".
To compute , we can run a dfs from from vertex and check if you can reach vertex for all . If we can't, then print if you're running the DFS on and otherwise.
Proof
Let's do a proof by contradiction. Assume that is true for all vertices in both and , and there exists a pair of vertices such that . Since is true in , then must be true in . Additionally, must be true in . So, you can travel from , which contradicts the statement that . Thus, is true for all vertices .
Implementation
Time Complexity:
from typing import List, Setn, m = map(int, input().split())forward_graph = [[] for _ in range(n)]reverse_graph = [[] for _ in range(n)]for _ in range(m):a, b = map(int, input().split())forward_graph[a - 1].append(b - 1)
The problem can also be solved using strongly connected components (SCC).
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!