这题求最大异或值的时候直接按照 x×popcount(x) 作为关键字排序,暴力往后找 50000 个即可通过。
这下充分发扬人类智慧了。
代码如下:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
int n, d[maxn], cnt, ans = -1;
struct data {
int to, weight;
};
vector<data> G[maxn];
bool cmp(int a, int b) {
return a * __builtin_popcount(a) > b * __builtin_popcount(b);
}
inline void dfs(int u, int fa) {
for (auto i : G[u]) {
int v = i.to, w = i.weight;
if (v == fa) continue;
d[v] = d[u] ^ w;
dfs(v, u);
}
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> n;
for (int i = 1; i < n; i++) {
int u, v, w;
cin >> u >> v >> w;
G[u].push_back({v, w});
G[v].push_back({u, w});
}
dfs(1, 1);
sort(d + 1, d + n + 1, cmp);
int m = min(n, 50000);
for (int i = 1; i <= m; i++) {
for (int j = i + 1; j <= m; j++) {
ans = max(ans, d[i] ^ d[j]);
}
}
cout << ans;
return 0;
}