标签:最小生成树
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
struct edge{int from, to, cost;}E[50009];
int rank[10008 * 2], par[10008 * 2];
void init(int n) {
for (int i = 0; i < 10008 * 2; i++) {
par[i] = i;
rank[i] = 0;
}
}
int find(int x) {
if(par[x] == x) return x;
else return par[x] = find(par[x]);
}
void unite(int x, int y) {
x = find(x), y = find (y);
if (x == y) return;
if (rank[x] > rank[y]) par[y] = x;
else {
par[x] = y;
if (rank[x] == rank[y]) rank[y]++;
}
}
bool same(int x, int y) { return find(x) == find(y); }
bool cmp(const edge e1, const edge e2) { return e1.cost < e2.cost;}
int kruskal(int r, int n) {
int res = 0, count = 1;
sort(E, E + r, cmp);
for (int i = 0; i < r; i++) {
if (!same(E[i].from, E[i].to)) {
unite(E[i].from, E[i].to);
res += E[i].cost;
count++;
}
}
return res + (n - count + 1) * 10000;
}
int main(void) {
int t;
scanf("%d", &t);
while (t--) {
int n, m, r;
scanf("%d%d%d", &n, &m, &r);
n += m;
init(n);
for (int i = 0; i < r; i++) {
scanf("%d%d%d", &E[i].from, &E[i].to, &m);
E[i].cost = 10000 - m;
E[i].to += 10000;
}
printf("%d\n", kruskal(r, n));
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:最小生成树
原文地址:http://blog.csdn.net/jibancanyang/article/details/47038951