problems / 165

Next Free Locker

hard segment-tree binary-search simulation 1000 ms · 256 MB

Next Free Locker

A gym's front desk hands out lockers through a small kiosk. There are n lockers numbered 1 to n, and when the gym opens every locker is free.

Members do not always want the first free locker: someone whose friend is already inside may ask for "the third free one" to end up nearby. The kiosk therefore supports two commands:

  • TAKE k — find the k-th free locker in increasing order of locker number, mark it as taken and print its number. If fewer than k lockers are currently free, nothing changes and the kiosk prints -1.
  • RELEASE i — a key is returned for locker i, so locker i becomes free. If locker i is already free (a stray key, or one returned twice), nothing changes.

Process the commands in the given order.

Input

The first line contains two integers n and q (1 ≤ n ≤ 10^6, 1 ≤ q ≤ 5·10^5) — the number of lockers and the number of commands.

Each of the next q lines contains one command, either TAKE k (1 ≤ k ≤ n) or RELEASE i (1 ≤ i ≤ n).

Output

For every TAKE command, print one line with the number of the assigned locker, or -1 if fewer than k lockers are free. RELEASE commands produce no output.

Notes

In the first example, TAKE 2 assigns locker 2. The free lockers are then 1, 3, 4, 5, so TAKE 3 assigns locker 4. Now only 1, 3, 5 are free, so TAKE 4 prints -1. RELEASE 2 makes lockers 1, 2, 3, 5 free, and TAKE 2 assigns locker 2 again. RELEASE 3 is ignored because locker 3 is already free, so TAKE 3 sees the free lockers 1, 3, 5 and assigns locker 5. Finally TAKE 1 assigns locker 1.

In the second example there is a single locker, and a TAKE fails whenever it is occupied.

Example 1

Input

5 8
TAKE 2
TAKE 3
TAKE 4
RELEASE 2
TAKE 2
RELEASE 3
TAKE 3
TAKE 1

Output

2
4
-1
2
5
1

Example 2

Input

1 6
TAKE 1
TAKE 1
RELEASE 1
RELEASE 1
TAKE 1
TAKE 1

Output

1
-1
1
-1

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

Hint 1

A TAKE needs the position of the k-th free locker, and scanning from locker 1 costs O(n) per command. Which structure can count the free lockers in a prefix and change one flag in O(log n)?

Hint 2

Use a Fenwick tree (or segment tree) over 0/1 free flags, and find the k-th one by descending the tree. Keep a separate flag array so that releasing an already-free locker changes nothing.

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

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