All problems

Problem 400

Frequency Stack

Hard · 30 pts · Stack, Hash Table, Design

Problem

Simulate a frequency stack. 'push x' adds x. 'pop' removes and prints the most frequent element currently in the stack; if several elements are tied for the highest frequency, it removes the one that was pushed most recently among them. Pop is only called on a non-empty stack. Keeping a separate stack for each frequency level gives O(1) per operation.

Input

First line: Q. Next Q lines: 'push x' or 'pop'.

Output

Print the value removed by each pop, one per line.

Constraints

1 <= Q <= 20000; 0 <= x <= 1000000000; pop is never called on an empty stack; at least one pop

Example input

10
push 5
push 7
push 5
push 7
push 4
push 5
pop
pop
pop
pop

Example output

5
7
5
4

Explanation

After pushing 5 7 5 7 4 5, the value 5 appears three times, so the first pop returns 5. Now 5 and 7 both appear twice, and 7 was pushed more recently, so the next pop returns 7.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Median of a Data Stream Next: Level Sums of a Binary Tree