Problem Author: | Mohammad Nasser (MOAGEZA) |
Prepared by: | Mohammad Nasser (MOAGEZA) |
Edited by: | Hasan Saleh (MathModel) |
Solution
General Idea: We want the minimum number of bit flips such that there exists a subarray whose bitwise OR equals .
Observe that flipping a bit position is equivalent to forcing that bit to match the corresponding bit in . Thus, for any subarray with OR value , the number of required operations is simply the number of differing bits:
So the task reduces to efficiently enumerating all possible subarray OR values.
Key Observation: When iterating through the array from left to right, the number of distinct OR values of subarrays ending at position is small — at most about .
Why? Because every time we apply OR, bits can only change from to . Since integers have at most bits, each bit can be set only once.
Algorithm: Maintain a vector that stores pairs (value, start) representing distinct OR values for subarrays ending at the current index.
For each element:
Start a new subarray with OR equal to .
OR it with all previously stored values.
Merge duplicates to keep the vector small.
For every OR value , compute \text{popcount}(x \oplus k) and update the answer.
Finally, output the bit positions that differ between the best OR value and .
Complexity Analysis:
Although it may seem that we are checking many subarrays, the number of distinct OR values per index is bounded by the number of bits (at most ).
For each of the elements, we process at most distinct OR values.
Therefore, the time complexity is:
Space complexity: \mathcal{O}(30) = \mathcal{O}(1) for storing distinct OR values at each position.
Reference Implementation
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n, k;
cin >> n >> k;
vector<int> a(n + 1);
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
vector<pair<int, int>> v;
int ans = 30, pos = 0;
for (int i = 1; i <= n; i++) {
vector<pair<int, int>> u;
u.push_back({a[i], 1});
for (auto [x, c] : v) {
int g = (x | a[i]);
if (g == u.back().first) {
u.back().second = c;
} else {
u.push_back({g, c});
}
}
v = u;
for (auto [x, c] : v) {
int cnt = (x ^ k);
int res = __builtin_popcount(cnt);
if (res <= ans) {
ans = res;
pos = cnt;
}
}
}
cout << ans << "\n";
for (int i = 0; i < 30; i++) {
if (pos & (1 << i)) {
cout << i << " ";
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
solve();
cout << "\n";
}
return 0;
}