最小生成树Kruskal算法。
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXN = 1005;
const int MAXM = 20005;
int n, m, a, b, l;
int cost[MAXN][MAXN];
int par[MAXN];
int rank[MAXN];
struct edge {
int x;
int y;
int cost;
}es[MAXN];
bool cmp(const edge& e1, const edge& e2) {
return e1.cost < e2.cost;
}
void init(int n) {
for(int i=0; i<n; 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[x] = y;
else {
par[y] = x;
if(rank[x] == rank[y]) rank[x]++;
}
}
bool same(int x, int y) {
return find(x) == find(y);
}
int main() {
scanf("%d%d", &n, &m);
int ids = 0;
for(int i=0; i<m; i++) {
scanf("%d%d%d", &a, &b, &l);
es[ids].x = a;
es[ids].y = b;
es[ids++].cost = l;
}
sort(es, es+m, cmp);
init(n);
int res = 0;
int max = -1;
for(int i=0; i<m; i++) {
edge e = es[i];
if(!same(e.x, e.y)) {
unite(e.x, e.y);
max = max > e.cost ? max : e.cost;
}
}
printf("%d\n", max);
return 0;
}