Given a partial order of comparisons between students in line, recover a card permutation consistent with all pairs or print -1.
Hard8Topological sortSortingGraphGreedyNo attempts yetTime limit2sMemory limit512 MBN students stand in one line, one behind another. Each student holds a single card, and the cards carry distinct numbers from 1 to N. Every student handed in a complete list of the students who stand behind them and hold a card with a smaller number. The task is to recover each student's card number from those lists.
Suppose five students stand in line and are called student 1, student 2, student 3, student 4, student 5 from the front. A pair (X,Y) means that student Y stands behind student X and holds a card with a smaller number. If the lists give the pairs (1,2), (1,5), (3,4), (3,5), (4,5), then student 1 through student 5 hold the cards 3, 1, 5, 4, 2 in that order.
Now suppose the same five students give the pairs (1,2), (1,3), (1,5), (2,5), (3,4), (3,5). Those lists are wrong. By the pair (2,5), student 2 holds a larger number than student 5. If student 4 held a smaller number than student 5, the pair (2,4) would have to appear, and if student 4 held a larger number, the pair (4,5) would have to appear. Neither pair is present, so no assignment of cards fits.
Write a program that reads the pairs built from the lists and reports the card number of each student.
The first line holds the number of students N (1≤N≤100,000) and the number of pairs M (0≤M≤1,000,000), separated by a space. The students are called student 1, student 2, ..., student N from the front of the line. Each of the next M lines holds two natural numbers X and Y separated by a space (1≤X<Y≤N). Such a pair means that student Y holds a card with a smaller number than student X. No pair is given twice.
If the given pairs determine the card numbers, print them on one line in the order the students stand, separated by spaces. Otherwise print -1.