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
2019-01-18 16:55:53
use Kahn's algo with priority_queue. good beginner question for topo sort
2019-01-18 16:55:52
also don't forget '.' in cycle case output :P

Last edit: 2019-01-18 16:57:20
2018-12-27 11:20:42
learned two different methods for topological sort...good question :)
2018-12-19 15:15:57
Make sure you have put '.' in "Sandro fails."
2018-11-20 12:30:43
first number have to be smallest or second number !!!???
2018-11-03 12:40:38
easy , AC in one go...!!
2018-09-21 22:00:56
6 4
5 1
1 2
2 3
4 6
output:4 5 1 2 3 6


Last edit: 2018-12-27 21:05:59
2018-06-26 17:45:32
*If there are multiple solutions print the one, whose first number is smallest* Use <set> instead of <vector>. Plus cin and cout works!
2018-05-29 00:05:51
Its always better to use printf and scanf than to waste your whole day.
2018-02-18 12:35:30
nice one:)
© Spoj.com. All Rights Reserved. Spoj uses Sphere Engine™ © by Sphere Research Labs.