【BZOJ1232】[Usaco2008Nov]安慰奶牛cheer【最小生成树】

【题目链接】

用新边权w'(u, v) = w(u, v) + val(u) + val(v)跑一次最小生成树,然后找一个点权最小的点当做起点。

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

using namespace std;

const int maxn = 10005, maxm = 100005, inf = 0x3f3f3f3f;

int n, m, c[maxn], 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] ? x : fa[x] = find(fa[x]);
}

int main() {
	int ans = inf;
	n = iread(); m = iread();
	for(int i = 1; i <= n; i++) fa[i] = i, c[i] = iread(), ans = min(ans, c[i]);
	for(int i = 1; i <= m; i++) {
		int u = iread(), v = iread(), w = iread();
		g[i] = (_edge){u, v, (w << 1) + c[u] + c[v]};
	}

	sort(g + 1, g + 1 + m);
	int cnt = 0;
	for(int i = 1; i <= m && cnt != n - 1; i++) {
		int u = find(g[i].u), v = find(g[i].v);
		if(u != v) {
			cnt++;
			ans += g[i].w;
			fa[u] = v;
		}
	}

	printf("%d\n", ans);
	return 0;
}


你可能感兴趣的:(【BZOJ1232】[Usaco2008Nov]安慰奶牛cheer【最小生成树】)