-
Notifications
You must be signed in to change notification settings - Fork 5
/
GFG_PageFaultsInLRU.cpp
90 lines (71 loc) · 1.85 KB
/
GFG_PageFaultsInLRU.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
https://practice.geeksforgeeks.org/problems/page-faults-in-lru5603/1#
Page Faults in LRU
*/
// { Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class LRUCache {
public:
list<pair<int,int>> cache;
unordered_map<int, list<pair<int,int>>::iterator> cacheMap;
int capacity_;
LRUCache(int capacity) : capacity_(capacity){
// capacity_ = capacity;
}
// int get(int key)
// {
// if(cacheMap.find(key) == cacheMap.end())
// return -1;
// cache.splice(cache.begin(), cache, cacheMap[key]); // transfer to front
// return cacheMap[key]->second; // return its value
// }//
int put(int key, int value)
{
if(cacheMap.find(key) != cacheMap.end())
{
cache.splice(cache.begin(), cache, cacheMap[key]);
cacheMap[key]->second = value;
return 0;
}
if(cache.size() == capacity_)
{
cacheMap.erase(cache.back().first);
cache.pop_back();
}
cache.push_front({key, value});
cacheMap[key] = cache.begin();
return 1;
}//
};
class Solution{
public:
int pageFaults(int N, int C, int pages[]){
LRUCache lru = LRUCache(C);
int faults=0;
for(int p=0; p<N; p++)
{
faults += lru.put(pages[p], pages[p]);
}
return faults;
}
};
// { Driver Code Starts.
int main(){
int t;
cin>>t;
while(t--){
int N, C;
cin>>N;
int pages[N];
for(int i = 0;i < N;i++)
cin>>pages[i];
cin>>C;
Solution ob;
cout<<ob.pageFaults(N, C, pages)<<"\n";
}
return 0;
} // } Driver Code Ends