noi.ac #39 MST

MST 模板题

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>

using namespace std;
const int N = 5e5 + 10;

#define LL long long
#define gc getchar()
#define Rep(i, a, b) for(int i = a; i <= b; i ++)

inline int read() {
	int x = 0;
	char c = gc;
	while(c < '0' || c > '9') c = gc;
	while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = gc;
	return x;
}

struct Node {
	int u, v, w;
	bool operator < (const Node a) const {
		return this-> w > a.w;
	}
} E[N];
int fa[N];
LL Answer, tot;
int n, m;

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

void Kruskal() {
	int js = 0;
	Rep(i, 1, m) {
		int u = E[i].u, v = E[i].v, fau = Get(u), fav = Get(v);
		if(fau != fav) {
			fa[fau] = fav;
			Answer += E[i].w;
			js ++;
		}
		if(js == n - 1) return ;
	}
}

int main() {
	n = read(), m = read();
	Rep(i, 1, m) {
		E[i] = (Node) {
			read(), read(), read()
		};
		tot += E[i].w;
	}
	Rep(i, 1, n) fa[i] = i;
	sort(E + 1, E + m + 1);
	Kruskal();
	cout << tot - Answer;
	return 0;
}
原文地址:https://www.cnblogs.com/shandongs1/p/9720291.html