【题解】ACOJ12194|BZOJ1682|USACO2005 Mar|干草危机

最小生成树板子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
struct edge{
int u, v, w;
}graph[20005];

inline int read()
{
int x = 0,f = 1;char ch = getchar();
while(ch < '0' || ch > '9'){if(ch == '-')f = -1;ch = getchar();}
while(ch >= '0' && ch <= '9'){x = x * 10 + ch - '0';ch = getchar();}
return x * f;
}

int n, m, tot;
int fa[2005];

bool cmp(edge a, edge b){
return a.w < b.w;
}
int find(int x){
if(x == fa[x]) return x;
return fa[x] = find(fa[x]);
}

int main(){
n = read();m = read();
for(int i = 1;i <= n;i ++) fa[i] = i;
for(int i = 1;i <= m;i ++) graph[i].u = read(), graph[i].v = read(), graph[i].w = read();
sort(graph + 1, graph + m + 1, cmp);
for(int i = 1;;i ++){
int p = find(graph[i].u), q = find(graph[i].v);
if(p != q)
{
fa[p] = q;tot ++;
if(tot == n - 1)
{
cout << graph[i].w;
break;
}
}
}
return 0;
}