USACO 2018 US Open Contest, Gold Problem 2. Milking Order
Farmer John'scows ( ), numbered as always, happen to have too much time on their hooves. As a result, they have worked out a complex social hierarchy related to the order in which Farmer John milks them every morning.
After weeks of study, Farmer John has madeobservations about his cows' social structure ( ). Each observation is an ordered list of some of his cows, indicating that these cows should be milked in the same order in which they appear in this list. For example, if one of Farmer John's observations is the list 2, 5, 1, Farmer John should milk cow 2 sometime before he milks cow 5, who should be milked sometime before he milks cow 1.
Farmer John's observations are prioritized, so his goal is to maximize the value offor which his milking order meets the conditions outlined in the first observations. If multiple milking orders satisfy these first conditions, Farmer John believes that it is a longstanding tradition that cows with lower numbers outrank those with higher numbers, so he would like to milk the lowest-numbered cows first. More formally, if multiple milking orders satisfy these conditions, Farmer John would like to use the lexicographically smallest one. An ordering is lexicographically smaller than an ordering if for some , for all and (in other words, the two orderings are identical up to a certain point, at which is smaller than ).
Please help Farmer John determine the best order in which to milk his cows.
INPUT FORMAT (file milkorder.in):
The first line containsand . The next lines each describe an observation. Line describes observation , and starts with the number of cows listed in the observation followed by the list of integers giving the ordering of cows in the observation. The sum of the 's is at most .
OUTPUT FORMAT (file milkorder.out):
Outputspace-separated integers, giving a permutation of containing the order in which Farmer John should milk his cows.
4 3 3 1 2 3 2 4 2 3 3 4 1
1 4 2 3
Here, Farmer John has four cows and should milk cow 1 before cow 2 and cow 2 before cow 3 (the first observation), cow 4 before cow 2 (the second observation), and cow 3 before cow 4 and cow 4 before cow 1 (the third observation). The first two observations can be satisfied simultaneously, but Farmer John cannot meet all of these criteria at once, as to do so would require that cow 1 come before cow 3 and cow 3 before cow 1.
This means there are two possible orderings: 1 4 2 3 and 4 1 2 3, the first being lexicographically smaller.