Live Latency Median

medium heap 1000 ms · 256 MB

Live Latency Median

A monitoring agent watches a web service and records the response time of every request, in milliseconds. The dashboard shows one number next to the service: the median response time of all requests seen so far, refreshed after every new sample.

The agent receives n samples t_1, t_2, …, t_n in order. After the i-th sample arrives, sort the first i samples in non-decreasing order and take the element at position ⌈i/2⌉ (1-based). That is, for an odd count take the middle element, and for an even count take the lower of the two middle elements. Report this value after every sample.

Input

The first line contains n (1 ≤ n ≤ 2·10^5), the number of samples.

The second line contains n integers t_1, t_2, …, t_n (1 ≤ t_i ≤ 10^9), the response times in milliseconds, in the order they arrive. Values may repeat.

Output

Print n lines. The i-th line must contain the median of t_1, …, t_i as defined above.

Notes

In the first example, after the fourth sample the times seen are 40, 120, 35, 90. Sorted, they are 35, 40, 90, 120; the two middle elements are 40 and 90, and the dashboard shows the lower one, 40. After the fifth sample (60) the sorted list is 35, 40, 60, 90, 120 and the median is 60.

The reported value is always one of the samples; it is never an average.

Example 1

Input

6
40 120 35 90 60 60

Output

40
40
40
40
60
60

Example 2

Input

4
500 400 300 200

Output

500
400
400
300

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

Hint 1

After each sample you only need one element of the sorted prefix, not the whole order. Which elements can ever be that median, and how far apart do the smaller half and the larger half need to be?

Hint 2

Keep the smaller half of the samples in a max-heap and the larger half in a min-heap, so the answer is the top of the first heap. Each new sample needs only a constant number of heap operations, as long as you keep the sizes balanced in the right way for an even count.

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

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