Springs of the Forking River

medium binary-search-tree stack monotonic-stack trees sorting 1000 ms · 256 MB

Springs of the Forking River

An old river splits in two at every landmark along its course. At a landmark numbered x, the river sends one branch downstream to the left and another to the right, and the split obeys a strict rule: every landmark reachable down the left branch is numbered lower than x, every landmark reachable down the right branch is numbered higher than x, and in fact every landmark anywhere in x's left branch is numbered lower than every landmark anywhere in x's right branch. Landmark numbers never repeat. Eventually each branch reaches a spring, a landmark with no further fork.

A boat put in at the source always follows this rule at each fork: explore the whole left branch first, then come back and explore the whole right branch. The expedition's log lists the landmarks in the order the boat first passes them.

You are given the log. Using only the splitting rule above, figure out which landmarks are springs (landmarks with no fork), and print them in the order they appear from the leftmost branch of the river to the rightmost.

Input

The first line contains an integer n (1 ≤ n ≤ 2·10^5), the number of landmarks in the log.

The second line contains n distinct integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), the landmark numbers in the order the boat's log records them. The splitting rule above is guaranteed to be consistent with some arrangement of forks, i.e. the log is a valid such traversal of some river.

Output

Print the spring landmarks, from the leftmost branch of the river to the rightmost, as space-separated integers on a single line. Every river has at least one spring.

Notes

In the first example the river forks at 8 into a left branch containing {5, 1, 7} and a right branch containing {10, 9, 12}; 5 forks again into {1} and {7}, and 10 forks into {9} and {12}. The springs, left to right, are 1, 7, 9, 12.

Example 1

Input

7
8 5 1 7 10 9 12

Output

1 7 9 12

Example 2

Input

5
1 2 3 4 5

Output

5

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

Hint 1

The splitting rule is the ordering rule of a binary search tree, and the log is its preorder traversal, so the springs are the tree's leaves. Since every left branch lies below every right branch, in what order do the leaves appear from left to right? The question left is which landmarks have no child.

Hint 2

Scan the log once while keeping a stack of landmarks whose right branch may still be open. Each new landmark is either the left child of the stack top or the right child of the last landmark it closes, so mark whichever parent it attaches to. The landmarks never marked are the springs, and they come out sorted by value.

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

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