Advertisement
Md_Ahad

HSTU Contest C

Jul 4th, 2025 (edited)
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long int ll;
  4. const ll N = 1e5+7;
  5. ll arr[N], cnt[N][21];
  6.  
  7. ll andValue(ll l, ll r) {
  8.     ll indx = 0;
  9.     for (ll j = 20; j >= 0; j--) {
  10.         if (cnt[r][j]-cnt[l-1][j] == r-l+1) indx += (1LL << j);
  11.     }
  12.     return indx;
  13. }
  14.  
  15. bool valid(ll l, ll r, ll j) {
  16.     return (cnt[r][j] - cnt[l-1][j] == r-l+1);
  17. }
  18.  
  19. signed main() {
  20.     ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  21.     ll t = 1; cin >> t;
  22.  
  23.     while (t--) {
  24.         ll n, q; cin >> n >> q;
  25.  
  26.         for (ll i = 1; i <= n; i++) {
  27.             cin >> arr[i];
  28.             for (ll j = 20; j >= 0; j--) {
  29.                 if (arr[i] & (1LL << j)) cnt[i][j] = 1;
  30.                 else cnt[i][j] = 0;
  31.             }
  32.             for (ll j = 20; j >= 0; j--) cnt[i][j] += cnt[i-1][j];
  33.         }
  34.  
  35.         while (q--) {
  36.             ll l, r; cin >> l >> r;
  37.            
  38.             ll ans = andValue(l, r-1) + andValue(r, r);
  39.             for (ll j = 0; j <= 20; j++) {
  40.                 if (arr[l] & (1LL << j)) {
  41.                     ll low = l, high = r-1, indx = l;
  42.                    
  43.                     while (low <= high) {
  44.                         ll mid = low + (high-low) / 2;
  45.                         if (valid(l, mid, j)) {
  46.                             low = mid+1;
  47.                             indx = mid;
  48.                         }
  49.                         else high = mid-1;
  50.                     }
  51.                     ans = max(ans, andValue(l, indx) + andValue(indx+1, r));
  52.                 }
  53.             }
  54.            
  55.             cout << ans << "\n";
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement