Sinks of a Graph

Time limit1sMemory limit128 MB

Summary
In each directed graph, list every node v such that every node reachable from v can reach v back.
Level

Medium7 of 10

Topics
Graph, DFS, Implementation, Sorting
Solved
No attempts yet

Problem

You are given a directed graph G=(V,E)G = (V, E).

For any two nodes u,v∈Vu, v \in V, if there is a path from uu to vv using only edges in EE, we write u→vu \to v.

A node v∈Vv \in V is called a sink if every node reachable from vv has a path back to vv; that is, if it satisfies the following condition:

∀w∈V, (v→w)  ⟹  (w→v)\forall w \in V,\ (v \to w) \implies (w \to v)

The set of all sinks of GG is denoted bottom(G)\mathrm{bottom}(G).

bottom(G)={ v∈V:∀w∈V, (v→w)  ⟹  (w→v) }\mathrm{bottom}(G) = \{\, v \in V : \forall w \in V,\ (v \to w) \implies (w \to v) \,\}

Given the graph G=(V,E)G = (V, E), compute bottom(G)\mathrm{bottom}(G).

Input

The input consists of several test cases.

The first line of each test case contains the number of nodes nn (1≤n≤5 0001 \le n \le 5\,000) and a non-negative integer mm (0≤m≤100 0000 \le m \le 100\,000). This means V={1,2,…,n}V = \{1, 2, \dots, n\} and the number of edges is ∣E∣=m|E| = m.

Then follow mm integer pairs v1 w1 v2 w2 … vm wmv_1\ w_1\ v_2\ w_2\ \dots\ v_m\ w_m separated by whitespace, where each pair (vi,wi)(v_i, w_i) denotes an edge (vi,wi)∈E(v_i, w_i) \in E. These integers may span multiple lines.

The input ends with a value of nn equal to 00; such a test case must not be processed, and the program should terminate.

Output

For each test case, print all nodes in bottom(G)\mathrm{bottom}(G) on one line, sorted in ascending order and separated by spaces. If bottom(G)\mathrm{bottom}(G) is empty, print an empty line.

Examples2

  1. Example 1

    Input
    3 3
    1 3 2 3 3 1
    2 1
    1 2
    0
    
    Expected output
    1 3
    2
    
  2. Example 2

    Input
    2 1
    2 1
    2 0
    
    5 5
    1 2 2 3 3 1 5 4 4 3
    5 5
    1 2 2 3 3 1 3 4 4 5
    5 1
    5 1
    5 6
    1 2 2 3 3 1 3 4 4 5 5 3
    0
    
    Expected output
    1
    1 2
    1 2 3
    5
    1 2 3 4
    1 2 3 4 5