-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathP1111 修复公路.cpp
66 lines (57 loc) · 1.05 KB
/
P1111 修复公路.cpp
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1001;
const int MAXM = 100001;
struct v{
int x, y, z;
friend bool operator <(v a, v b){
return a.z < b.z;
}
};
int n, m, ans = -1, father[MAXN], totcount;
v g[MAXM];
int find_root(int x) {
if(father[x]!=-1) {
return father[x] = find_root(father[x]);
}
return x;
}
int union_(v a) {
int x_root = find_root(a.x);
int y_root = find_root(a.y);
if(x_root!=y_root) {
father[x_root] = y_root;
return 1;
}
return 0;
}
int main() {
memset(father, -1, sizeof(father));
cin>>n>>m;
if(m < n - 1) {//至少有n-1条边才能联通
cout<<-1<<endl;
return 0;
}
else{
for(int i=0; i<m; i++) {
cin>>g[i].x>>g[i].y>>g[i].z;
}
sort(g, g+m);//重载了小于号
for(int i=0; i<m; i++) {
if(union_(g[i])) {//判断
ans = max(ans, g[i].z);//答案
totcount++;
}
if(totcount>n-1) {//提前跳出
break;
}
}
if(totcount<n-1) {//同理,不能联通
cout<<-1<<endl;
}
else{
cout<<ans<<endl;
}
}
return 0;
}