Advertisement
Guest User

Untitled

a guest
Sep 1st, 2020
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <string>
  5. #include <algorithm>
  6. #include <set>
  7. #include <cassert>
  8. using namespace std;
  9.  
  10. struct Node{
  11. Node* next;
  12. Node* prev;
  13. int value;
  14. int key;
  15. Node(Node* p, Node* n, int k, int val):prev(p),next(n),key(k),value(val){};
  16. Node(int k, int val):prev(NULL),next(NULL),key(k),value(val){};
  17. };
  18.  
  19. class Cache{
  20.  
  21. protected:
  22. map<int,Node*> mp; //map the key to the node in the linked list
  23. int cp; //capacity
  24. Node* tail; // double linked list tail pointer
  25. Node* head; // double linked list head pointer
  26. virtual void set(int, int) = 0; //set function
  27. virtual int get(int) = 0; //get function
  28.  
  29. };
  30.  
  31. #include <list> //EDITABLE AREA STARTS HERE
  32. #include <iterator>
  33.  
  34. class LRUCache : public Cache {
  35.  
  36. protected:
  37. std::list<int> liList;
  38.  
  39. public:
  40. LRUCache(int capacity);
  41.  
  42.  
  43. void set(int key, int value) {
  44.  
  45. list<int>::iterator it = this->liList.begin();
  46.  
  47. this->liList.insert(it, key-1, value);
  48.  
  49. int size = this->liList.size();
  50.  
  51. if(size >= this->cp) {
  52. list<int>::iterator it2 = this->liList.end();
  53. liList.erase(it2);
  54. }
  55. }
  56.  
  57. int get(int key) {
  58. list<int>::iterator it = this->liList.begin();
  59.  
  60. std::advance(it, key-1);
  61.  
  62. liList.erase(it);
  63.  
  64. int temp = *it;
  65.  
  66. liList.push_front(temp);
  67.  
  68. return temp;
  69. }
  70. }; //EDITABLE AREA ENDS HERE
  71.  
  72. int main() {
  73. int n, capacity,i;
  74. cin >> n >> capacity;
  75. LRUCache l(capacity);
  76. for(i=0;i<n;i++) {
  77. string command;
  78. cin >> command;
  79. if(command == "get") {
  80. int key;
  81. cin >> key;
  82. cout << l.get(key) << endl;
  83. }
  84. else if(command == "set") {
  85. int key, value;
  86. cin >> key >> value;
  87. l.set(key,value);
  88. }
  89. }
  90. return 0;
  91. }
  92.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement