-
Notifications
You must be signed in to change notification settings - Fork 0
/
lru.cpp
45 lines (45 loc) · 1.33 KB
/
lru.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <bits/stdc++.h>
using namespace std;
int pageFaults(vector<int> &pages, int capacity) {
unordered_set<int> s;
unordered_map<int, int> indexes;
int page_faults = 0;
for (int i = 0; i < pages.size(); i++) {
if (s.size() < capacity) {
if (s.find(pages[i]) == s.end()) {
s.insert(pages[i]);
page_faults++;
}
indexes[pages[i]] = i;
} else {
if (s.find(pages[i]) == s.end()) {
int lru = INT_MAX, val;
for (auto it = s.begin(); it != s.end(); it++) {
if (indexes[*it] < lru) {
lru = indexes[*it];
val = *it;
}
}
s.erase(val);
s.insert(pages[i]);
page_faults++;
}
indexes[pages[i]] = i;
}
}
return page_faults;
}
int main() {
int n, capacity;
cout << "Enter the number of pages: ";
cin >> n;
vector<int> pages(n);
cout << "Enter the page sequence: ";
for (int i = 0; i < n; ++i) {
cin >> pages[i];
}
cout << "Enter the capacity of cache: ";
cin >> capacity;
cout << "Number of page faults: " << pageFaults(pages, capacity) << endl;
return 0;
}