Problem 738
Page Faults in LRU
Medium · 20 pts · Design, Hash Table, Simulation
Problem
A computer's memory holds at most C pages. Pages are requested in the given order. If a requested page is already in memory it is a hit; otherwise it is a page fault, the page is loaded, and if memory was full the least recently used page (the one whose last request is oldest) is removed first. Count the page faults. A hash map with insertion order, or a list plus a map, simulates this in O(1) per request.
Input
The first line contains N and C. The second line contains the N page numbers in request order.
Output
Print the number of page faults.
Constraints
1 <= N <= 100000; 1 <= C <= 1000; 0 <= page <= 10^9
Example input
9 4 5 0 1 3 2 4 1 0 5
Example output
8
Explanation
With C = 4 and requests 5 0 1 3 2 4 1 0 5, the first four requests fault. Then 2 evicts 5, 4 evicts 0, 1 is a hit, 0 evicts 3, and 5 evicts 2. That makes 8 faults.