Problem 595
LFU Cache
Hard · 30 pts · Design, Hash Table, Linked List
Problem
Simulate a least frequently used (LFU) cache with capacity C. Every key has a use counter: put creates it with counter 1, and each later get or put on that key adds 1. 'get k' prints the value of k, or -1 if it is absent. 'put k v' stores v for k; if k is new and the cache is full, first evict the key with the smallest counter, and among ties the one used least recently. Keep one ordered bucket of keys per counter value plus the current minimum counter for O(1) operations.
Input
The first line contains C and Q. Each of the next Q lines contains 'put k v' or 'get k'. There is at least one get.
Output
Print the result of every get operation, one per line.
Constraints
1 <= C <= 10000; 1 <= Q <= 200000; 0 <= k, v <= 10^5
Example input
2 10 put 1 1 put 2 2 get 1 put 3 3 get 2 get 3 put 4 4 get 1 get 3 get 4
Example output
1 -1 3 -1 3 4
Explanation
With C = 2: after put 1, put 2 and get 1 (prints 1), key 1 has counter 2 and key 2 has 1. put 3 evicts key 2, so get 2 prints -1 and get 3 prints 3. Now keys 1 and 3 both have counter 2; put 4 evicts key 1 (used less recently), so get 1 is -1, and get 3 and get 4 print 3 and 4.