Milking Order
Time limit2sMemory limit512 MB
Find the largest prefix of M ordered cow lists that stays acyclic, then output the lexicographically smallest topological order of that graph.
- Level
Hard8 of 10
- Topics
- Graph, Topological sort, Binary search, Greedy
- Solved
- No attempts yet
Problem
Farmer John's cows (), numbered as always, have far too much time on their hooves. They have worked out a complex social hierarchy around the order in which Farmer John milks them every morning.
After weeks of study, Farmer John has made observations about that hierarchy (). Each observation is an ordered list of some of his cows, and it means those cows must be milked in the order in which they appear in the list. For example, if one observation is the list 2, 5, 1, Farmer John must milk cow 2 sometime before cow 5, and cow 5 sometime before cow 1.
The observations are prioritized, so Farmer John wants to maximize the value of for which his milking order meets the conditions of the first observations. If several milking orders satisfy those first conditions, a longstanding tradition says that cows with lower numbers outrank cows with higher numbers, so Farmer John milks the lowest-numbered cows first. More formally, he uses the lexicographically smallest such ordering. An ordering is lexicographically smaller than an ordering if for some , for all and : the two orderings agree up to a point, at which is smaller.
Help Farmer John determine the best order in which to milk his cows.
Input
The first line contains and . Each of the next lines describes one observation. Line describes observation : it starts with the number of cows listed in the observation, followed by the cow numbers in the observed order. The sum of the is at most .
Output
Output space-separated integers forming a permutation of , the order in which Farmer John should milk his cows.
Note
In the first example, Farmer John has four cows. The first observation says to milk cow 1 before cow 2 and cow 2 before cow 3. The second says to milk cow 4 before cow 2, and the third says to milk cow 3 before cow 4 and cow 4 before cow 1. The first two observations hold together, but all three at once would require cow 1 before cow 3 and cow 3 before cow 1, which is impossible. That leaves two possible orderings, 1 4 2 3 and 4 1 2 3, and the lexicographically smaller one is 1 4 2 3.