Skip to main content
Tuesday (24.11.2026) at 20:00: ALGOR Contest: Round #4 (Special Challenge) starts!

~/algor $ cat problems/topologik-saralash

Topological sort

Medium 1000 ms 128 MB 64%
Share

A graph with $n$ vertices and $m$ directed edges is given. The vertices are numbered from $1$ to $n$. Write out all vertices in an order (a topological order) such that for every edge $u \to v$ vertex $u$ comes before $v$. If there are several valid orders, print the lexicographically smallest one. If the graph has a cycle, print $-1$.

A directed graph and its vertices in topological order

Input

The first line contains two integers: $n$ and $m$. Each of the next $m$ lines contains two positive integers: $u$ and $v$ — an edge $u \to v$.

Output

One line: $n$ space-separated integers — the topological order, or $-1$ if there is a cycle.

Note

$1 \le n \le 10^{5}$
$0 \le m \le 2 * 10^{5}$
$1 \le u, v \le n$

Examples

Input #1
4 3
1 2
2 4
3 4
Output #1
1 2 3 4
Input #2
3 3
1 2
2 3
3 1
Output #2
-1

Sign in to submit a solution

Signing up is free and takes a minute.