Saturday, January 27, 2024

[Hackerearth] OrOasis

 

Problem Link    : OrOasis 
Category        : Binary Search, Xor
Contest         : January Circuits '24

#include "bits/stdc++.h"
using namespace std;
// #define int     long long int
#define endl    '\n'
 
const int BITS = 31;
 
void solve() {
    int n;
    cin >> n;
    vector<int> nums(n);
    int total = 0;
    vector<vector<int>> cumBits(n, vector<int>(BITS));
    for (int i = 0; i < n; i++) {
        cin >> nums[i];
        total |= nums[i];
        for (int b = BITS - 1; b >= 0; b--) {
            bool val = (nums[i] >> b & 1);
            cumBits[i][b] = val;
            if (i - 1 >= 0) {
                cumBits[i][b] += cumBits[i - 1][b];
            }
        }
    }
    function<int(int, int)> GetOr = [&](int l, int r) {
        if (r >= n or l > r) {
            return 0;
        }
        int orsum = 0;
        for (int b = BITS - 1; b >= 0; b--) {
            int cnt = cumBits[r][b];
            if (l - 1 >= 0) {
                cnt -= cumBits[l - 1][b];
            }
            if (cnt) {
                orsum |= (1LL << b);
            }
        }
        return orsum;
    };
    int minlen = INT_MAX;
    int ans = 0;
    for (int i = 0; i < n; i++) {
        int lo = i;
        int hi = n - 1;
        int id = -1;
        while (lo <= hi) {
            int mid = (lo + hi) >> 1;
            int x = GetOr(i, mid);
            if (x == total) {
                id = mid;
                hi = mid - 1;
            } else {
                lo = mid + 1;
            }
        }
        if (id != -1) {
            int x = GetOr(i, id);
            int y = GetOr(0, i - 1) | GetOr(id + 1, n - 1);
            if (x ^ y) {
                continue;
            }
            int len = id - i + 1;
            if (len < minlen) {
                minlen = len;
                ans = 1;
            } else if (minlen == len) {
                ans++;
            }
        }
    }
    if (minlen >= n) {
        cout << -1 << endl;
    } else {
        cout << minlen << " " << ans << endl;
    }
}
 
signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr); cout.tie(nullptr);
    cout.precision(12);
 
    bool FILEIO = true; string FILE = "in.txt";
    if (FILEIO and fopen(FILE.c_str(), "r")) {
        freopen(FILE.c_str(), "r", stdin);
    }
 
    int tc;
    cin >> tc;
    for (int tcase = 1; tcase <= tc; tcase++) {
        solve();
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.