problems / 143

Nearest Price Level

easy binary-search-tree trees binary-search 1000 ms · 256 MB

Nearest Price Level

A matching engine keeps, for one instrument, the set of active price levels: integer prices (in ticks) at which at least one order currently rests. When a market-maker bot wants to quote near some price x, it asks the engine for the nearest active level at or below x, or at or above x.

You are given a log of q operations, processed in order. The set of active levels starts empty. Each operation is one of:

  • ADD x: price level x becomes active. If x is already active, nothing changes.
  • REMOVE x: price level x becomes inactive. If x is not active, nothing changes.
  • FLOOR x: report the highest active level that is less than or equal to x.
  • CEIL x: report the lowest active level that is greater than or equal to x.

A level is either active or not: adding the same level twice and then removing it once leaves it inactive.

Input

The first line contains an integer q (1 ≤ q ≤ 2·10^5), the number of operations.

Each of the next q lines contains an operation name (ADD, REMOVE, FLOOR or CEIL, in upper case) and an integer x (1 ≤ x ≤ 10^9), separated by a single space.

Output

For every FLOOR and CEIL operation, in the order they appear, print one line with the requested price level, or NONE if no active level satisfies the condition.

If there are no FLOOR or CEIL operations, print nothing.

Notes

In the first example, after levels 100, 105 and 98 are added, FLOOR 103 finds 100 and CEIL 103 finds 105. CEIL 106 prints NONE because no active level is at or above 106. After 100 is removed, FLOOR 103 falls back to 98. FLOOR 98 prints 98 itself, since the bound is inclusive.

In the second example, level 7 is added twice but becomes inactive after a single REMOVE, and REMOVE 3 is ignored because level 3 was never active.

Example 1

Input

10
ADD 100
ADD 105
ADD 98
FLOOR 103
CEIL 103
CEIL 106
REMOVE 100
FLOOR 103
FLOOR 98
FLOOR 97

Output

100
105
NONE
98
98
NONE

Example 2

Input

9
CEIL 5
ADD 7
ADD 7
REMOVE 3
CEIL 1
REMOVE 7
CEIL 1
ADD 2
FLOOR 1000000000

Output

NONE
7
NONE
2

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

Hint 1

Each query asks for a neighbour of x in sorted order, while the set of levels keeps changing. Which kind of structure keeps a set sorted under insertions and deletions and answers predecessor and successor queries?

Hint 2

Both bounds are inclusive, so an active x answers both FLOOR and CEIL. Check how you turn "first element at or above x" and "last element at or below x" into your structure's search calls, and what to print when that search runs off either end.

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

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