Alice's Guessing Tree

medium binary-search-tree trees segment-tree 2000 ms · 256 MB

Alice's Guessing Tree

Alice is building a number-guessing game. She starts with an empty binary search tree and then inserts n distinct integers, one at a time, in a fixed order she has chosen in advance. Insertion follows the ordinary textbook rule and the tree is never rebalanced: to insert a value v, start at the root and repeatedly step to the left child if v is smaller than the current node's value or to the right child if v is larger, until there is no child to step to; v becomes a new leaf there (the very first value becomes the root).

Bob will play the game: he will be given a value and must find it by walking down from the root exactly the way Alice's tree was built, comparing v against one node at a time. The number of comparisons Bob needs equals the number of edges on the path from the root to that value's node — its depth, where the root has depth 0.

Before the game starts, Alice asks you to tell Bob, for every value, what its depth will be once all n values have been inserted. Since every new value is attached as a fresh leaf, a value's depth never changes after it is inserted, so this is simply the depth of each value in the final tree.

Input

The first line contains a single integer n (1 ≤ n ≤ 2·10^5) — the number of values.

The second line contains n pairwise distinct integers a_1, a_2, …, a_n (-10^9 ≤ a_i ≤ 10^9) — the values in the exact order Alice inserts them.

Output

Print n integers separated by spaces: the depth of a_1, a_2, …, a_n respectively, each counted in the final tree (root depth is 0).

Notes

In the first example, Alice inserts 5 (the root, depth 0), then 3 (goes left of 5, depth 1), then 8 (goes right of 5, depth 1), then 1 (goes left of 5, then left of 3, depth 2).

Building the tree directly with real node pointers is correct but can take O(n^2) time when the insertion order is already sorted or nearly sorted (the tree degenerates into a long chain), which is too slow for the given limits.

Example 1

Input

4
5 3 8 1

Output

0 1 1 2

Example 2

Input

6
10 20 15 12 -7 25

Output

0 1 2 3 1 2

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

Hint 1

Building the tree with pointers is too slow when the values arrive in sorted order. Think about where a new value sits relative to the values already inserted, in sorted order.

Hint 2

When a value v arrives, its nearest smaller and nearest larger values already in the tree are neighbours in sorted order. Which of those two is the parent of v, and how does that give v's depth?

Hint 3

Keep the values inserted so far in an ordered structure, such as a balanced set or a Fenwick or segment tree over compressed values, so you can find the predecessor and successor of each new value in logarithmic time.

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

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