Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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
- };
- #include <list> //EDITABLE AREA STARTS HERE
- #include <iterator>
- class LRUCache : public Cache {
- protected:
- std::list<int> liList;
- public:
- LRUCache(int capacity);
- void set(int key, int value) {
- list<int>::iterator it = this->liList.begin();
- this->liList.insert(it, key-1, value);
- int size = this->liList.size();
- if(size >= this->cp) {
- list<int>::iterator it2 = this->liList.end();
- liList.erase(it2);
- }
- }
- int get(int key) {
- list<int>::iterator it = this->liList.begin();
- std::advance(it, key-1);
- liList.erase(it);
- int temp = *it;
- liList.push_front(temp);
- return temp;
- }
- }; //EDITABLE AREA ENDS HERE
- 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;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement