TOPOSORT - Topological Sorting

Sandro is a well organised person. Every day he makes a list of things which need to be done and enumerates them from 1 to n. However, some things need to be done before others. In this task you have to find out whether Sandro can solve all his duties and if so, print the correct order.

Input

In the first line you are given an integer n and m (1 <= n <= 10000, 1 <= m <= 1000000). On the next m lines there are two distinct integers x and y, (1 <= x, y <= 10000) describing that job x needs to be done before job y.

Output

Print "Sandro fails." if Sandro cannot complete all his duties on the list. If there is a solution print the correct ordering, the jobs to be done separated by a space. If there are multiple solutions print the one, whose first number is smallest, if there are still multiple solutions, print the one whose second number is smallest, and so on.

Example 1

Input:
8 9
1 4
1 2
4 2
4 3
3 2
5 2
3 5
8 2
8 6

Output:
1 4 3 5 7 8 2 6 

Example 2

Input:
2 2
1 2
2 1

Output:
Sandro fails.

Added by:Josef Ziegler
Date:2011-10-23
Time limit:0.5s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All

hide comments
2021-05-29 17:59:45
Use kahn's algorithm using min heap(priority queue) or set.
And no need to worry about cycles as topological order doesn't exists in cyclic graph so check the size of the resulting vector after calculating topological order if it is equal to n then order exists else no


Last edit: 2021-05-29 18:00:52
2021-04-16 05:56:19
kahn's algo+set as queue
2021-04-02 15:27:57
who is send here to this question by codencode youtube channel guys
2021-02-15 12:51:59
Java solution accepting and we have to print the solution in lexicographic smallest order if multiple solution exist
which costed me 2 times WA
2021-01-03 23:51:05
Why do we need to dfs from n to 1?
2020-10-12 15:43:56
u can use dfs with set. AC in one go!!!
2020-09-24 16:19:07
If you are getting TLE (using either Kahns algo with priority queue OR by using version of dfs) make sure your cycle detection part is optimal. Cycle detection should happen in O(V+E)
2020-08-19 16:03:59
kahn's algo in Python giving TLE
Anyone is having solution in python?
2020-08-17 08:28:46
Solved using Kahn's Algo. Used set instead of queue. AC.
2020-08-15 21:45:43
If there is a solution print the correct ordering, the jobs to be done separated by a whitespace.

If there are multiple solutions print the one, whose first number is smallest, if there are still multiple solutions, print the one whose second number is smallest, and so on.


Last edit: 2020-08-15 21:46:20
© Spoj.com. All Rights Reserved. Spoj uses Sphere Engine™ © by Sphere Research Labs.