All problems

Problem 167

Smallest Topological Order

Medium · 20 pts · Graph, Topological Sort, Heap

Problem

You are given a directed graph with N nodes and M edges. A topological order lists all nodes so that for every edge u → v, node u comes before node v. Print the lexicographically smallest topological order: at each position, the smallest node number that can go there. If the graph has a cycle, no topological order exists, so print -1. Use Kahn's algorithm with a min-heap instead of a plain queue: repeatedly take the smallest node whose remaining in-degree is 0, output it, and decrease the in-degree of its neighbours. If fewer than N nodes are output, there is a cycle.

Input

First line: integers N and M. Next M lines: a directed edge u v (u -> v).

Output

Print the order, space-separated, or -1.

Constraints

1 <= N <= 100000; 0 <= M <= 200000

Example input

4 4
1 2
1 3
2 4
3 4

Example output

1 2 3 4

Explanation

At first only node 1 has no incoming edges, so it comes first. Removing it frees nodes 2 and 3; the smaller one, 2, goes next, then 3. Node 4 needs both 2 and 3 and comes last. The order is 1 2 3 4.

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

Previous: Is Graph Bipartite Next: Course Schedule