#B3782. Paper Ordering

    ID: 11439 Type: Default 1000ms 256MiB

Paper Ordering

Paper Ordering

zyl has n pieces of paper (numbered from 1 to n). They were written at different times but no date is marked on them. zyl needs to arrange them in the order of writing time. He can judge the order by the continuity of the content on the papers. For each paper, you are given its following information:

  • First, an integer m is provided. If m > 0, it indicates that in the continuous content immediately following this paper, there are m papers. Then, m integers are given in chronological order denoting the paper numbers of these papers.
  • If m = 0 (i.e. the paper is the last in a contiguous segment), then a single integer is given representing the next paper determined by its damage degree. If there is no such paper, the number will be -1.

Your task is to help zyl reconstruct the full chronological order of the papers. It is guaranteed that the input information results in a unique ordering covering all papers.

Note: For any paper that appears as part of a continuous segment from another paper, its own information is considered redundant and should be ignored when reconstructing the order.

The final ordering can be obtained as follows:

  1. Find the starting paper (the one with no incoming pointer from any other paper).
  2. Let the current paper be x; output x.
  3. If the information for x has m > 0, append the given continuous list of paper numbers (in order) to the output and update x as the last paper in that segment.
  4. If m = 0, then let d be the given damage pointer. If d = -1, the ordering is complete; otherwise, update x to d and output it.
  5. Repeat step 3 and 4 until the sequence is complete.

inputFormat

The first line contains a single integer n (1 ≤ n ≤ 10^5), representing the number of papers. The following n lines each contain the information for one paper (the papers are numbered from 1 to n). For each paper, the line begins with an integer m.

If m > 0, it is followed by m space‐separated integers which denote the paper numbers of the papers that immediately follow in the continuous content (in chronological order).

If m = 0, it is followed by one integer which is the next paper number determined by damage degree. If there is no such paper, the integer will be -1.

It is guaranteed that the information provided leads to a unique complete ordering of the papers.

outputFormat

Output the n paper numbers in chronological order, separated by a space.

sample

5
1 4
2 3 5
0 -1
0 -1
0 1
2 3 5 1 4