Advertisement
tepyotin2

Buying Gift

Jun 23rd, 2025
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1.  #include <bits/stdc++.h>
  2.  
  3.  using namespace std;
  4.  
  5.  typedef long long ll;
  6.  
  7.  struct Department{
  8.      ll a, b;
  9.      bool operator<(const Department& v) const{
  10.          return a<v.a;
  11.      }
  12. };
  13.  
  14.  int t;
  15.  
  16.  int main(){
  17.      //freopen("buyinggifts.in", "r", stdin);
  18.      
  19.      cin >> t;
  20.      while(t--){
  21.          int n;
  22.          cin >> n;
  23.          vector<Department> dep(n);
  24.          vector<ll> mx(n, -1);
  25.          for(int i=0; i<n; i++){
  26.              cin >> dep[i].a >> dep[i].b;
  27.          }
  28.          sort(dep.begin(), dep.end());
  29.          ll mxv = -1;
  30.          //!!!Need to use base values as -1 to check with right values at line 41 because there are some
  31.          //values that are possibly equal to 0;
  32.          for(int i=n-1; i>=0; i--){
  33.              mx[i] = mxv;
  34.              mxv = max(mxv, dep[i].b);
  35.              //Get suffix to compare later on in calculation
  36.          }
  37.          set<ll> works;
  38.          ll ans = LLONG_MAX;
  39.          for(int i=0; i<n; i++){
  40.              if(i<n-1){
  41.                  ans = min(ans, abs(mx[i]-dep[i].a));
  42.                  //check with max values because max values are always valid
  43.              }
  44.              if(dep[i].a>mx[i] && !works.empty()){
  45.                  auto it = works.upper_bound(dep[i].a);
  46.                  //get upper_bound and check out of bounds to see which values work under top condition
  47.                  //on line 44
  48.                  if(it!=works.end()){
  49.                      ans = min(ans, abs(*it-dep[i].a));
  50.                  }
  51.                  //it--;
  52.                  if(it!=works.begin()){
  53.                      it--;
  54.                      ans = min(ans, abs(*it-dep[i].a));
  55.                  }
  56.              }
  57.              works.insert(dep[i].b);
  58.              //Keep values that can be valid to be used
  59.          }
  60.          cout << ans << '\n';
  61.      }
  62.      
  63.      return 0;
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement