All problems

Problem 931

Minimum Number of Vertices to Reach All Nodes

Medium · 20 pts · Graph

Problem

A directed acyclic graph has N nodes numbered 0 to N - 1. Find the smallest set of nodes from which every node can be reached, and print it in increasing order. This set is unique: a node with an incoming edge can always be reached from somewhere else, while a node with no incoming edges can only be reached from itself. So the answer is exactly the nodes with in-degree 0.

Input

The first line contains N and M. Each of the next M lines contains a directed edge u v (from u to v).

Output

Print the nodes with no incoming edge in increasing order, separated by spaces.

Constraints

2 <= N <= 100000; 1 <= M <= 100000; the graph is acyclic and edges are distinct

Example input

6 5
0 1
0 2
2 5
3 4
4 2

Example output

0 3

Explanation

With edges 0→1, 0→2, 2→5, 3→4 and 4→2 on 6 nodes, only nodes 0 and 3 have no incoming edge. Starting from them reaches every node, so the answer is 0 3.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: All Paths From Source to Target Next: Loud and Rich