题解 UOJ176 【新年的繁荣】
完全图 MST 不一定要用 Borvuka 做。
首先可以将
由于边权种数很少,只有
一个暴力的想法是对当前
但直接做的时间复杂度为
考虑参考 FMT 进行优化:我们每次只枚举
时间复杂度为
代码:
#include <stdio.h>
typedef long long ll;
int pos[262147], root[262147];
inline void init(int n, int m){
for (int i = 0; i <= n; i++){
pos[i] = -1;
}
for (int i = 1; i <= m; i++){
root[i] = i;
}
}
int get_root(int x){
if (root[x] == x) return x;
return root[x] = get_root(root[x]);
}
inline bool merge(int x, int y){
int root_x = get_root(x), root_y = get_root(y);
if (root_x == root_y) return false;
root[root_x] = root_y;
return true;
}
int main(){
int n, m, full;
ll ans = 0;
scanf("%d %d", &n, &m);
full = (1 << m) - 1;
init(full, n);
for (int i = 1; i <= n; i++){
int a;
scanf("%d", &a);
if (pos[a] == -1){
pos[a] = i;
} else {
ans += a;
}
}
for (int i = full; i >= 0; i--){
for (int j = 0; j < m; j++){
if (!(i >> j & 1)){
int x = i ^ (1 << j);
if (pos[i] == -1){
pos[i] = pos[x];
} else if (pos[x] != -1 && merge(pos[i], pos[x])){
ans += i;
}
}
}
}
printf("%lld", ans);
return 0;
}