Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <list>
- #include <unordered_map>
- class VideoHistory {
- private:
- std::list<int> history; // Doubly linked list to maintain order
- std::unordered_map<int, std::list<int>::iterator> videoMap; // Map to access list nodes in O(1)
- const size_t maxSize = 3;
- public:
- void watchVideo(int videoId) {
- // If video is already in history, remove it from its current position
- if (videoMap.find(videoId) != videoMap.end()) {
- history.erase(videoMap[videoId]);
- } else if (history.size() == maxSize) {
- // Remove the least recently used (last element)
- int lastVideo = history.back();
- videoMap.erase(lastVideo);
- history.pop_back();
- }
- // Add new video to the front (most recent)
- history.push_front(videoId);
- videoMap[videoId] = history.begin();
- }
- void printHistory() const {
- std::cout << "Video History (most recent first): ";
- for (int id : history) {
- std::cout << id << " ";
- }
- std::cout << std::endl;
- }
- };
- int main() {
- VideoHistory vh;
- vh.watchVideo(101);
- vh.watchVideo(102);
- vh.watchVideo(103);
- vh.printHistory(); // Output: 103 102 101
- vh.watchVideo(103);
- vh.printHistory(); // Output: 103 102 101 (103 moved to front, order same due to re-watch)
- vh.watchVideo(104);
- vh.printHistory(); // Output: 104 103 102 (101 evicted)
- vh.watchVideo(102);
- vh.printHistory(); // Output: 102 104 103
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement