AND-AND-AND
unknown
c_cpp
14 days ago
1.8 kB
3
Indexable
Never
#include<bits/stdc++.h> using namespace std ; using ll = long long ; #define ln "\n" ; void solve(){ ll n,k ; cin>>n>>k ; vector<ll>A(n) ; for(int i =0;i<n;i++){ cin>>A[i] ; } vector<vector<ll> >prefix(n,vector<ll>(31,0)) ; for(int i = 0 ;i<n;i++){ for(int j = 0 ;j<31;j++){ if((A[i]>>j)&1){ prefix[i][j]++ ; } } } for(int i = 1;i<n;i++){ for(int j = 0 ;j<31;j++){ prefix[i][j]+=prefix[i-1][j] ; } } vector<vector<ll> >nxt(n,vector<ll>(31,n)) ; for(int i = n-1;i>=1;i--){ for(int j = 0 ;j<31;j++){ if((A[i]>>j)&1){ nxt[i-1][j] = nxt[i][j] ; }else{ nxt[i-1][j] = i ; } } } ll ans = 1e9 ; for(int i = 0 ;i<n;i++){ ll val = A[i] ; vector<ll>temp ; temp.push_back(i) ; for(int j =0;j<31;j++){ ll x = nxt[i][j] ; if(x!=n){ temp.push_back(x) ; } } ll l = i ; for(int j =0;j<temp.size();j++){ ll r = temp[j] ; ll sub_ans = 0 ; for(int z = 0;z<31;z++){ ll y1 = prefix[r][z] ; if(l-1>=0){ y1-= prefix[l-1][z] ; } if(y1==(r-l+1)){ sub_ans|=(1<<z) ; } } ans = min(ans,abs(sub_ans-k)) ; } } cout<<ans<<ln ; } int main() { ios_base::sync_with_stdio(false) ; cin.tie(NULL) ; cout.tie(NULL) ; ll t; cin >> t; for(int it=1;it<=t;it++) { // cout << "Case #" << it+1 << ": "; solve(); } return 0; }
Leave a Comment