-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhr_abstract_classes_polymorphism.cpp
More file actions
69 lines (65 loc) · 1.74 KB
/
Copy pathhr_abstract_classes_polymorphism.cpp
File metadata and controls
69 lines (65 loc) · 1.74 KB
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
#include <map>
#include <string>
#include <iostream>
struct Node {
int key, value;
Node *next, *prev;
Node(const int& _key, const int& _value) : key(_key), value(_value),
next(), prev() { }
};
class Cache {
protected:
std::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;
virtual int get(int) = 0;
};
class LRUCache : public Cache {
public:
LRUCache(const int& _cp) : Cache() { cp = _cp; }
void set(int _key, int _value) override {
if (mp.find(_key) != mp.end()) {
mp[_key]->value = _value;
} else {
Node *nn = new Node(_key, _value); // new node
if (head) {
nn->next = head;
head->prev = nn;
}
head = nn;
if (!tail)
tail = head;
if (mp.size() == cp) { // capacity exhausted
mp.erase(tail->key);
tail = tail->prev;
}
mp[_key] = nn;
}
}
int get(int _key) override {
if (mp.find(_key) == mp.end())
return -1;
return mp[_key]->value;
}
};
int main() {
int n, capacity;
std::cin >> n >> capacity;
LRUCache l(capacity);
for (int i = 0; i < n; ++i) {
std::string command;
std::cin >> command;
if (command == "get") {
int key;
std::cin >> key;
std::cout << l.get(key) << std::endl;
} else if (command == "set") {
int key, value;
std::cin >> key >> value;
l.set(key, value);
}
}
return 0;
}