https://atcoder.jp/contests/abc281/tasks/abc281_f
Consider the following example:
0xxxx
0xxxx
0xxxx
0xxxx
If all integers at a certain bit are all $0$, then $x$ should be $0$ in this bit. vice versa, if all $1$, then $x$ should be $1$.
What if all integers at a certain bit contains both $0$ and $1$?
0xxxx 0xxxx 1xxxx 1xxxx
We divide these integers into two sets, $S_0$ represents all the integers where the digit is $0$ in the certain bit; $S_1$ represents $1$.
If we choose $x$ at that bit be $0$, then all these integers will not change, and $\min\{S_1\}>\max\{S_0\}$. That is the maximum integer after $\text{xor}$ must in $S_1$. Then in the next dfs, we don’t need to consider $S_0$. It is similar if the choice of $x$ at this bit is $1$, we don’t have to consider $S_1$.
// compile: g++ -o data data.cpp -O3 -std=gnu++20 -Wall -Wextra -Wshadow -D_GLIBCXX_ASSERTIONS -ggdb3 -fmax-errors=2 -DLOCAL
// run: ./data < data.in
#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#ifdef LOCAL
#include <debug/codeforces.h>
#define debug(x...) {_variables(#x);_print(x);}
#else
#define debug(x...)
#endif
template<typename...Args> void print_(Args...args){((cout<<args<<" "),...)<<endl;}
#define rep(i,a,b) for(int i=(a);i<(int)(b);++i)
#define sz(v) ((int)(v).size())
#define print(...) print_(__VA_ARGS__);
#define INTMAX (int)(9223372036854775807)
#define INTINF (int)(1152921504606846976)
#define int long long
#define MAXN 200010
int n, f[50], minv = INTINF;
void dfs(int k, vector<int> a, int ans) {
if (k < 0) {
minv = min(minv, ans);
return;
}
vector<int> s0, s1;
for (int i: a) {
if (i & (1 << k)) s1.push_back(i);
else s0.push_back(i);
}
if (s0.empty()) dfs(k - 1, s1, ans);
else if (s1.empty()) dfs(k - 1, s0, ans);
else {
dfs(k - 1, s1, ans | (1 << k));
dfs(k - 1, s0, ans | (1 << k));
}
}
int32_t main() {
ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
cin >> n; vector<int> a(n);
rep(i, 0, n) cin >> a[i];
dfs(30, a, 0);
cout << minv << endl;
return 0;
}
In xor problems, always consider the impact of each bit on the answer, especially for problems such as the maximum and minimum problem. Brute force is not a bad idea, sometimes there are very effective optimizations.