Advertisement
chevengur

СПРИНТ № 6 | Просто о сложности. Теория быстродействия | Урок 9: Амортизированная сложность

Apr 7th, 2024
1,033
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.31 KB | None | 0 0
  1. #include <algorithm>
  2. #include <deque>
  3. #include <string>
  4. #include <cassert>
  5. #include <iostream>
  6.  
  7. using namespace std;
  8.  
  9. struct Ticket {
  10.     int id;
  11.     string name;
  12. };
  13.  
  14. class TicketOffice {
  15. public:
  16.     // добавить билет в систему
  17.     void PushTicket(const string& name) {
  18.         ++last_id_;
  19.         tickets_.push_back({ last_id_, name });
  20.     }
  21.  
  22.     // получить количество доступных билетов
  23.     int GetAvailable() const {
  24.         return tickets_.size();
  25.     }
  26.  
  27.     // получить количество доступных билетов определённого типа
  28.     int GetAvailable(const string& name) const {
  29.         return count_if(tickets_.begin(), tickets_.end(), [name](const Ticket& key) {
  30.             return key.name == name;
  31.             });
  32.          
  33.     }
  34.  
  35.  
  36.     // отозвать старые билеты (до определённого id)
  37.     void Invalidate(int minimum) {
  38.         for (int i = 0; i < minimum; i++)
  39.         {
  40.             if (!tickets_.empty() && tickets_.front().id <= minimum) {
  41.                 tickets_.pop_front();
  42.             }
  43.         }
  44.     }
  45.  
  46. private:
  47.     int last_id_ = 0;
  48.     deque<Ticket> tickets_;
  49. };
  50.  
  51.  
  52. int main()
  53. {
  54.     TicketOffice tickets;
  55.  
  56.     tickets.PushTicket("Swan Lake"); // id - 0
  57.     tickets.PushTicket("Swan Lake"); // id - 1
  58.     tickets.PushTicket("Boris Godunov"); // id - 2
  59.     tickets.PushTicket("Boris Godunov"); // id - 3
  60.     tickets.PushTicket("Swan Lake"); // id - 4
  61.     tickets.PushTicket("Boris Godunov"); // id - 5
  62.     tickets.PushTicket("Boris Godunov"); // id - 6
  63.  
  64.     cout << tickets.GetAvailable() << endl; // Вывод: 7
  65.     cout << tickets.GetAvailable("Swan Lake") << endl; // Вывод: 3
  66.     cout << tickets.GetAvailable("Boris Godunov") << endl; // Вывод: 4
  67.  
  68.     // Invalidate удалит билеты с номерами 0, 1, 2:
  69.     tickets.Invalidate(3);
  70.  
  71.     cout << tickets.GetAvailable() << endl; // Вывод: 4
  72.     cout << tickets.GetAvailable("Swan Lake") << endl; // Вывод: 1
  73.     cout << tickets.GetAvailable("Boris Godunov") << endl; // Вывод: 3
  74.  
  75.     tickets.PushTicket("Swan Lake"); // id - 7
  76.     tickets.PushTicket("Swan Lake"); // id - 8
  77.  
  78.     cout << tickets.GetAvailable("Swan Lake") << endl; // Вывод: 3
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement