题目链接:https://codeforces.com/contest/1624/problem/G
题意简述:给定一个图,求其中的一棵树,保证所有节点联通,使得树的所有边权或值最小。
题解:并查集+位处理。因为最终结果是根据或操作决定的,显然希望高位尽可能没有。所以可以从高位向低位遍历,去除掉当前位为1的所有边获取一个缩小后的子图。如果缩小后的子图不满足其中存在树使得所有节点连通,说明该比特位要加入到答案中;否则该缩小子图合法可以进行传递下去。
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int t, n, m, fa[N];
int find(int x) {
return fa[x] == x ? x : fa[x] = find(fa[x]);
}
bool merge(int x, int y) {
x = find(x);
y = find(y);
if (x != y) {
fa[y] = x;
return true;
}
return false;
}
void init() {
for (int i = 1; i <= n; i++) fa[i] = i;
}
struct Edge {
int u, v, w;
};
int main(void) {
// freopen("in.txt", "r", stdin);
ios::sync_with_stdio(false);
cin >> t;
while (t--) {
cin >> n >> m;
vector<Edge> e;
e.resize(m);
for (int i = 0; i < m; i++) {
cin >> e[i].u >> e[i].v >> e[i].w;
}
int ans = 0;
for (int pos = 30; pos >= 0; pos--) {
init();
int num = n;
vector<Edge> ne;
for (int i = 0; i < e.size(); i++) {
if (((e[i].w >> pos) & 1) == 0) {
ne.push_back(e[i]);
int x = e[i].u;
int y = e[i].v;
if(merge(x, y)) num--;
}
}
if (num == 1) e = ne;
else ans |= 1 << pos;
}
cout << ans << "\n";
}
return 0;
}