跳到正文

题解

题解 UOJ176 【新年的繁荣】

Leasier约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年7月27日
篇幅
约 3 分钟

版本

  1. v1当前

完全图 MST 不一定要用 Borvuka 做。


首先可以将 aa 去重:对于 i≠j,ai=aji \neq j, a_i = a_j,连边 (i,j)(i, j) 显然不劣,答案加上 aia_i。

由于边权种数很少,只有 O(2m)O(2^m) 种,考虑从大到小枚举每种边权 ww。

一个暴力的想法是对当前 ww,维护 aposw=wa_{pos_w} = w,枚举超集 w⊂w′w \subset w',若 posw′pos_{w'} 存在则将 posw,posw′pos_w, pos_{w'} 加入边集并删去 posw′pos_{w'}。

但直接做的时间复杂度为 O(n+3mlog⁡n)O(n + 3^m \log n),显然不能通过。

考虑参考 FMT 进行优化:我们每次只枚举 w′=w∪{x}w' = w \cup \{x\}(其中 x∉wx \not\in w)进行处理。若 poswpos_w 不存在,我们令其为任意存在的 posw′pos_{w'}。

时间复杂度为 O(n+m2mlog⁡n)O(n + m 2^m \log n)。

代码:

C++
#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;
}