Advertisement
Beingamanforever

EDU DIV2 B alternate binary search solution

Oct 28th, 2024 (edited)
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1.  
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());
  5. #define NeedForSpeed                  \
  6.     ios_base::sync_with_stdio(false); \
  7.     cin.tie(NULL);                    \
  8.     cout.tie(NULL);
  9. #define int long long
  10. #define all(x) (x).begin(), (x).end()
  11. typedef vector<int> vi;
  12. typedef vector<bool> vb;
  13. typedef vector<vi> vvi;
  14. typedef vector<pair<int, int>> vpi;
  15. #define f first
  16. #define s second
  17. #define endl "\n"
  18. const int mod = 1000000007;
  19. int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
  20. vi a;
  21. bool check(int mid)
  22. {
  23.     int cnt = 0;
  24.     int n = a.size();
  25.     for (int i = 1; i < n; i++)
  26.     {
  27.         if ((a[i] - a[i - 1]) <= mid)
  28.         {
  29.             cnt++;
  30.             i++;
  31.         }
  32.     }
  33.     return cnt >= (n / 2);
  34. }
  35. void solve()
  36. {
  37.     // as in n = even all the consecutive elements would be covered so number of pairs = n/2
  38.     // as in n = odd all but one would be covered, and the one can be compensated by atmost condition
  39.     int n;
  40.     cin >> n;
  41.     a.resize(n);
  42.     for (int i = 0; i < n; i++)
  43.     {
  44.         cin >> a[i];
  45.     }
  46.     sort(all(a));
  47.     int low = 1, high = 3e18, ans = high;
  48.     while (low <= high)
  49.     {
  50.         int mid = low + (high - low) / 2;
  51.         if (check(mid))
  52.         {
  53.             ans = mid;
  54.             high = mid - 1;
  55.         }
  56.         else
  57.         {
  58.             low = mid + 1;
  59.         }
  60.     }
  61.     cout << ans << endl;
  62.     return;
  63. }
  64.  
  65. signed main()
  66. {
  67.     NeedForSpeed;
  68.     int t = 1;
  69.     cin >> t;
  70.     while (t--)
  71.     {
  72.         solve();
  73.     }
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement