problems / 119

Merging Sorted Feeds

easy heap 2000 ms · 256 MB

Merging Sorted Feeds

A dashboard aggregates k live feeds. Each feed has already been sorted on its own: the values it reports arrive in non-decreasing order. Your job is to combine all k feeds into a single stream that is sorted overall.

You are given the full contents of all k feeds up front, as k sequences of integers, each already sorted in non-decreasing order (a feed may be empty). Output every value from every feed, across all of them, in non-decreasing order.

Input

The first line contains k (1 ≤ k ≤ 10^5), the number of feeds.

Each of the next k lines describes one feed: it starts with m (0 ≤ m), the number of values in that feed, followed by m integers v_1 ≤ v_2 ≤ … ≤ v_m (-10^9 ≤ v_i ≤ 10^9), the feed's values in non-decreasing order. A feed may have m = 0, in which case the line contains only 0.

The total number of values across all feeds, N = Σ m, satisfies 0 ≤ N ≤ 10^6.

Output

Print all N values from all feeds combined, in non-decreasing order, separated by single spaces, on one line. If N = 0, print an empty line.

Notes

In the first example, feed 1 is [1, 4, 9], feed 2 is empty, and feed 3 is [2, 2, 5]. Merging them gives 1, 2, 2, 4, 5, 9.

Since only the values are printed (not which feed they came from), the expected output is simply the multiset of all values across all feeds, sorted in non-decreasing order — there is exactly one correct output.

Example 1

Input

3
3 1 4 9
0
3 2 2 5

Output

1 2 2 4 5 9

Example 2

Input

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

Output

-1000000000 -5 -5 0 3 1000000000

Hints · reveal one at a time if you're stuck

Hint 1

Every feed is already sorted, so you do not need to re-sort all the values. At each step only the first unread value of each feed matters. Which feed should you take the next value from?

Hint 2

Keep one entry per non-empty feed in a min-heap holding that feed's current head. Pop the smallest, output it, and push that feed's next value if there is one. Use buffered input and output, since there can be a million values.

report an issue Prefer your own editor? sooks prep 119 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.