-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathabstract-classes-polymorphism.cpp
72 lines (66 loc) · 1.62 KB
/
abstract-classes-polymorphism.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
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <set>
#include <cassert>
using namespace std;
struct Node{
Node* next;
Node* prev;
int value;
int key;
Node(Node* p, Node* n, int k, int val):prev(p),next(n),key(k),value(val){};
Node(int k, int val):prev(NULL),next(NULL),key(k),value(val){};
};
class Cache{
protected:
map<int,Node*> mp; //map the key to the node in the linked list
int cp; //capacity
Node* tail; // double linked list tail pointer
Node* head; // double linked list head pointer
virtual void set(int, int) = 0; //set function
virtual int get(int) = 0; //get function
};
class LRUCache: public Cache {
private:
map<int,int> mymap;
map<int,int>::iterator it;
int capacity;
public:
LRUCache(int arg) {capacity = arg;}
int get(int key){
it = mymap.find(key);
if(key > capacity || it == mymap.end()) return -1;
else return it->second ;
}
void set(int key, int val){
mymap.erase(key);
mymap.insert(pair <int,int> (key,val));
if(mymap.size() > capacity){
it = mymap.end();
mymap.erase(it->first);
}
}
};
int main() {
int n, capacity,i;
cin >> n >> capacity;
LRUCache l(capacity);
for(i=0;i<n;i++) {
string command;
cin >> command;
if(command == "get") {
int key;
cin >> key;
cout << l.get(key) << endl;
}
else if(command == "set") {
int key, value;
cin >> key >> value;
l.set(key,value);
}
}
return 0;
}