Problem 282
Eventual Safe States
Medium · 20 pts · Graph, Topological Sort, Depth-First Search
Problem
You are given a directed graph with N nodes. A node is terminal if it has no outgoing edges. A node is safe if every path starting from it ends at a terminal node, so you can never get stuck walking around a cycle. Terminal nodes are safe. Print all safe nodes in increasing order, or NONE if there are none. Reverse the edges and run Kahn's algorithm from the terminal nodes: a node becomes safe once all of its outgoing edges lead to safe nodes. Nodes on a cycle, or with a path into a cycle, are never marked.
Input
First line: N and M. Next M lines: a directed edge u v.
Output
Print the safe nodes in increasing order, space-separated, or NONE.
Constraints
1 <= N <= 10000; 0 <= M <= 40000
Example input
7 7 1 2 1 3 2 3 2 4 3 6 4 1 5 6
Example output
3 5 6 7
Explanation
Nodes 1, 2 and 4 form the cycle 1 → 2 → 4 → 1, so a walk from them can go on forever. Node 3 leads only to the terminal node 6, node 5 also leads to 6, and 6 and 7 have no outgoing edges. The safe nodes are 3 5 6 7.