A factory builds one master assembly out of sub-components, and each of those sub-components may itself be built from smaller sub-components, and so on. For every component, its direct sub-components must be attached in a fixed left-to-right order, and a component cannot be marked finished until every one of its direct sub-components has already been finished (finishing a sub-component means its own entire sub-tree of parts is already complete). Given the full parts breakdown, output the order in which all components, including the master assembly itself, get marked finished.
Line 1: an integer N — the number of components, numbered 1..N, where component 1 is the master assembly (the root). Next N lines, one for each component from 1 to N in order: a line for component i begins with an integer k_i — the number of direct sub-components of component i — followed by k_i integers, the ids of those sub-components listed in the exact order they are attached (left to right). If k_i = 0 there are no further integers on that line.
Print a single line with the ids of all N components, space-separated, in the order they are finished.
1 <= N <= 10^5 0 <= k_i <= N-1 The sum of all k_i equals N-1. Every component id other than 1 appears as a direct sub-component of exactly one component, and together with the root this always forms a valid tree.
Example 1
Input
4 2 2 3 1 4 0 0
Expected
4 2 3 1
Explanation
Component 1 attaches component 2 first, then component 3. Component 2 needs component 4 finished first (component 4 has no sub-components, so it finishes immediately), then component 2 itself finishes. Next, component 3 (no sub-components) finishes. Finally component 1 finishes once both of its listed sub-components (2's whole subtree, then 3) are done. Finish order: 4 2 3 1.
Example 2
Input
1 0
Expected
1
Explanation
The master assembly has zero sub-components, so it finishes immediately by itself: the output is just "1".
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →