giGii

express

May 4th, 2023 (edited)
667
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.80 KB | None | 0 0
  1. #include <algorithm>
  2. #include <cmath>
  3. #include <iostream>
  4. #include <map>
  5. #include <string>
  6. #include <vector>
  7.  
  8. using namespace std;
  9.  
  10. class RouteManager {
  11. public:
  12.     void AddRoute(int start, int finish) {
  13.         reachable_lists_[start].push_back(finish);
  14.         reachable_lists_[finish].push_back(start);
  15.     }
  16.     int FindNearestFinish(int start, int finish) const {
  17.         int result = abs(start - finish);
  18.         if (reachable_lists_.count(start) < 1) {
  19.             return result;
  20.         }
  21.         const vector<int>& reachable_stations = reachable_lists_.at(start);
  22.         if (!reachable_stations.empty()) {
  23.             result = min(
  24.                          result,
  25.                          abs(
  26.                              finish - *min_element(
  27.                                                    reachable_stations.begin(),
  28.                                                    reachable_stations.end(),
  29.                                                      [finish](int lhs, int rhs) {
  30.                                                          return abs(lhs - finish) < abs(rhs - finish);
  31.                                                      }
  32.                               )
  33.                       )
  34.             );
  35.         }
  36.         return result;
  37.     }
  38.  
  39. private:
  40.     map<int, vector<int>> reachable_lists_;
  41. };
  42.  
  43. int main() {
  44.     RouteManager routes;
  45.  
  46.     int query_count;
  47.     cin >> query_count;
  48.  
  49.     for (int query_id = 0; query_id < query_count; ++query_id) {
  50.         string query_type;
  51.         cin >> query_type;
  52.         int start, finish;
  53.         cin >> start >> finish;
  54.         if (query_type == "ADD"s) {
  55.             routes.AddRoute(start, finish);
  56.         } else if (query_type == "GO"s) {
  57.             cout << routes.FindNearestFinish(start, finish) << "\n"s;
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment