【BZOJ1601】[Usaco2008 Oct]灌水【最小生成树】

【题目链接】

新加一个点,这个点与每个点连接边权为wi的边,跑最小生成树。

/* Pigonometry */
#include <cstdio>
#include <algorithm>

using namespace std;

const int maxn = 310, maxm = 90005;

int n, m, fa[maxn];

struct _edge {
	int u, v, w;

	bool operator < (const _edge &x) const {
		return w < x.w;
	}
} g[maxm];

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

inline int find(int x) {
	return x == fa[x] ? fa[x] : fa[x] = find(fa[x]);
}

int main() {
	n = iread(); m = 0;

	for(int i = 1; i <= n; i++) fa[i] = i, g[++m] = (_edge){n + 1, i, iread()};
	for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++)
		if(i ^ j) g[++m] = (_edge){i, j, iread()};
		else iread();
	fa[n + 1] = n + 1;

	sort(g + 1, g + 1 + m);

	int ans = 0;
	for(int i = 1, cnt = 0; cnt != n; i++) {
		int u = find(g[i].u), v = find(g[i].v);
		if(u != v) {
			ans += g[i].w;
			fa[u] = v;
			cnt++;
		}
	}
	printf("%d\n", ans);
	return 0;
}


你可能感兴趣的:(最小生成树)