problems / 172

Competitive Ranks (medium version)

medium ordered-set binary-search-tree design simulation 700 ms · 256 MB

Competitive Ranks (medium version)

An online multiplayer tournament tracks player ratings in real time. Players may join with an initial rating, update their current rating after each match, or leave the tournament entirely. At any point, organizers need to quickly look up who holds a particular rank.

You must support the following operations on the player rankings:

  1. JOIN name rating: Player name joins the tournament with the given rating. The player does not already exist.
  2. RATE name new_rating: Player name's rating is updated to new_rating. The player already exists.
  3. LEAVE name: Player name leaves the tournament. The player exists and will not appear in further RATE or LEAVE operations for this name.
  4. RANK r: Return the name of the player at rank r, where rank 1 is the player with the highest rating. If two players have the same rating, break ties alphabetically by player name (lexicographically smallest name comes first in rank order).

Input

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

Each of the next q lines is one of the operations above, in the format:

  • JOIN name rating
  • RATE name new_rating
  • LEAVE name
  • RANK r

where:

  • name is a non-empty string of up to 10 lowercase letters
  • rating and new_rating are integers in the range [1, 10^9]
  • r is a positive integer

Output

For each RANK query, print the name of the player at that rank on a separate line.

Notes

  • The problem is designed to be solved using a balanced binary search tree (ordered set) data structure, such as std::set in C++.
  • All RANK queries are guaranteed to have valid ranks (1 ≤ r ≤ number of active players).

Example 1

Input

7
JOIN alice 1000
JOIN bob 1200
RANK 1
RANK 2
RATE alice 1500
RANK 1
RANK 2

Output

bob
alice
alice
bob

Example 2

Input

8
JOIN charlie 1500
JOIN alice 1500
JOIN bob 1500
RANK 1
RANK 2
RANK 3
LEAVE alice
RANK 2

Output

alice
bob
charlie
charlie

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

Hint 1

A RANK query asks for the r-th player in a changing order, and walking the sorted set costs O(r) per query. What key should the players be sorted by, including the tie-break on name?

Hint 2

Keep a hash map from each name to its current rating, and remove the old (rating, name) entry before inserting the new one on RATE or LEAVE. Ordering the players by rating descending, then name ascending, makes each operation logarithmic.

Hint 3

An order-statistic tree answers the r-th query in O(log q). Offline, a Fenwick tree over every (rating, name) pair that ever appears, in rank order, works too.

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

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