Problem 271
Strongly Connected Components
Hard · 30 pts · Graph, Depth-First Search, Strongly Connected Component
Problem
In a directed graph, a strongly connected component is a largest possible group of nodes in which every node can reach every other node by following edges in their direction. Every node belongs to exactly one component, which may contain only that node. Count the strongly connected components. Use Kosaraju's algorithm (a DFS to get a finishing order, then DFS on the reversed graph in reverse finishing order) or Tarjan's algorithm. Both run in O(N + M). With up to 100,000 nodes, an iterative DFS avoids stack overflows.
Input
First line: N and M. Next M lines: a directed edge u v.
Output
Print the number of strongly connected components.
Constraints
1 <= N <= 100000; 0 <= M <= 200000
Example input
5 5 1 2 2 3 3 1 3 4 4 5
Example output
3
Explanation
Nodes 1, 2 and 3 form the cycle 1 → 2 → 3 → 1, so they are one component. Node 4 can be reached from 3 but cannot get back, and the same holds for 5. That gives 3 components: {1, 2, 3}, {4} and {5}.