Advertisement
thewitchking

Untitled

Jul 7th, 2025
349
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. #include <iostream>
  2. #include <list>
  3. #include <unordered_map>
  4.  
  5. class VideoHistory {
  6. private:
  7.     std::list<int> history; // Doubly linked list to maintain order
  8.     std::unordered_map<int, std::list<int>::iterator> videoMap; // Map to access list nodes in O(1)
  9.     const size_t maxSize = 3;
  10.  
  11. public:
  12.     void watchVideo(int videoId) {
  13.         // If video is already in history, remove it from its current position
  14.         if (videoMap.find(videoId) != videoMap.end()) {
  15.             history.erase(videoMap[videoId]);
  16.         } else if (history.size() == maxSize) {
  17.             // Remove the least recently used (last element)
  18.             int lastVideo = history.back();
  19.             videoMap.erase(lastVideo);
  20.             history.pop_back();
  21.         }
  22.  
  23.         // Add new video to the front (most recent)
  24.         history.push_front(videoId);
  25.         videoMap[videoId] = history.begin();
  26.     }
  27.  
  28.     void printHistory() const {
  29.         std::cout << "Video History (most recent first): ";
  30.         for (int id : history) {
  31.             std::cout << id << " ";
  32.         }
  33.         std::cout << std::endl;
  34.     }
  35. };
  36.  
  37. int main() {
  38.     VideoHistory vh;
  39.     vh.watchVideo(101);
  40.     vh.watchVideo(102);
  41.     vh.watchVideo(103);
  42.     vh.printHistory(); // Output: 103 102 101
  43.  
  44.     vh.watchVideo(103);
  45.     vh.printHistory(); // Output: 103 102 101 (103 moved to front, order same due to re-watch)
  46.  
  47.     vh.watchVideo(104);
  48.     vh.printHistory(); // Output: 104 103 102 (101 evicted)
  49.  
  50.     vh.watchVideo(102);
  51.     vh.printHistory(); // Output: 102 104 103
  52.  
  53.     return 0;
  54. }
  55.  
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement