Advertisement
dmkozyrev

task_1772

Apr 23rd, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. #include <iostream>
  2. #include <set>
  3.  
  4. using namespace std;
  5.  
  6. void compare_and_change(set<pair<int, long long int>> & s, pair<int, long long int> & p);
  7.  
  8. int main() {
  9.     int n, start, k, l, r;
  10.     cin >> n >> start >> k;
  11.    
  12.     set<pair<int, long long int>> s;
  13.     s.insert(pair<int, long long int>(start, 0));
  14.    
  15.     pair<int, long long int> left, right;
  16.     long long int dl, dr;
  17.    
  18.     for (int i = 0; i < k; ++i) {
  19.         cin >> l >> r;
  20.         auto first = s.lower_bound(pair<int,long long int>(l, 0));
  21.         if (first == s.end() || first->first > r)
  22.             continue;
  23.            
  24.         left.first = l-1;
  25.         left.second = 0;
  26.        
  27.         right.first = r+1;
  28.         right.second = 0;
  29.        
  30.         auto it = first;
  31.         while (it != s.end() && it->first <= r) {
  32.             dl = it->second+it->first-l+1;
  33.             dr = it->second+r-it->first+1;
  34.             if (left.second == 0 || left.second > dl)
  35.                 left.second = dl;
  36.             if (right.second == 0 || right.second > dr)
  37.                 right.second = dr;
  38.             it++;
  39.         }
  40.        
  41.         s.erase(first, it);
  42.        
  43.         if (l > 1) compare_and_change(s, left);
  44.         if (r < n) compare_and_change(s, right);
  45.     }
  46.    
  47.     long long int d = -1;
  48.     for (auto & it : s)
  49.         if (d == -1 || d > it.second)
  50.             d = it.second;
  51.     cout << d;
  52.     return 0;
  53. }
  54.  
  55. void compare_and_change(set<pair<int, long long int>> & s, pair<int, long long int> & p) {
  56.     auto it = s.lower_bound(pair<int, long long int>(p.first, 0));
  57.     if (it != s.end() && it->first == p.first) {
  58.         if (it->second > p.second) {
  59.             s.erase(it);
  60.             s.insert(p);
  61.         }
  62.     } else s.insert(p);
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement