Beingamanforever

Kefa and Company, Binary Search

Dec 12th, 2024
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. /**
  2.  *    author:  compounding
  3.  *    created: 2024-12-13 01:45:19
  4.  **/
  5. #include <bits/stdc++.h>
  6. using namespace std;
  7. mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());
  8. #define NeedForSpeed                  \
  9.     ios_base::sync_with_stdio(false); \
  10.     cin.tie(NULL);                    \
  11.     cout.tie(NULL);
  12. #define int long long
  13. #define all(x) (x).begin(), (x).end()
  14. typedef vector<int> vi;
  15. typedef vector<bool> vb;
  16. typedef vector<vi> vvi;
  17. typedef vector<pair<int, int>> vpi;
  18. #define f first
  19. #define s second
  20. #define yes cout << "YES" << endl
  21. #define no cout << "NO" << endl
  22. #define endl "\n"
  23. const int mod = 1000000007;
  24. int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
  25. void solve()
  26. {
  27.     int n, d;
  28.     cin >> n >> d;
  29.     vpi a(n);
  30.     for (int i = 0; i < n; i++)
  31.     {
  32.         cin >> a[i].f >> a[i].s;
  33.     }
  34.     sort(all(a));
  35.     vi p(n + 1, 0);
  36.     for (int i = 1; i <= n; i++)
  37.     {
  38.         p[i] = p[i - 1] + a[i - 1].s;
  39.     }
  40.     int mx = 0;
  41.     for (int i = 0; i < n; i++)
  42.     {
  43.         // we check for each index, the maximum segment we can take such that the difference is less than d
  44.         int l = i, r = n - 1, res = i;
  45.         while (l <= r)
  46.         {
  47.             int mid = (l + r) / 2;
  48.             if (a[mid].f - a[i].f < d)
  49.             {
  50.                 res = mid;
  51.                 l = mid + 1;
  52.             }
  53.             else
  54.             {
  55.                 r = mid - 1;
  56.             }
  57.         }
  58.         mx = max(mx, p[res + 1] - p[i]);
  59.     }
  60.     cout << mx << endl;
  61.     return;
  62. }
  63.  
  64. signed main()
  65. {
  66.     NeedForSpeed;
  67.     int t = 1;
  68.     // cin >> t;
  69.     while (t--)
  70.     {
  71.         solve();
  72.     }
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment