2019-5-9

https://www.luogu.org/problemnew/show/P1111

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cmath>
 4 #include<algorithm>
 5 using namespace std;
 6 typedef long long ll;
 7 int fa[100010];
 8 int n, m;
 9 int find(int x)
10 {
11     return x == fa[x] ? fa[x] : fa[x] = find(fa[x]);
12 }
13 void baba(int x, int y)
14 {
15     int fx = find(x);
16     int fy = find(y);
17     fa[fx] = fy;
18 }
19 struct node {
20     int from;
21     int to;
22     int jz;
23 }road[100010];
24 bool cmp(node a, node b)
25 {
26     return a.jz < b.jz;
27 }
28 bool same(int x, int y)
29 {
30     return find(x) == find(y);
31 }
32 int main()
33 {
34     cin >> n >> m;
35     for (int i = 1; i <= m; i++)
36     {
37         cin >> road[i].from >> road[i].to >> road[i].jz;
38     }
39     for (int i = 1; i <= m; i++)
40     {
41         fa[i] = i;
42     }
43     sort(road + 1, road + m + 1, cmp);
44     int t = 0;
45     int ans = 0;
46     for (int i = 1; i <= m; i++)
47     {
48         if (!same(road[i].from, road[i].to))
49         {
50             baba(road[i].from, road[i].to);
51             ans++;
52         }
53         if (ans == n - 1)
54         {
55             t = road[i].jz;
56             break;
57         }
58     }
59     if (t == 0)
60     {
61         printf("-1\n");
62     }
63     else
64     {
65         printf("%d\n", t);
66     }
67     return 0;
68 }

不要忘记fa数组的初始化

posted @ 2019-05-10 00:35  Fzzf1  阅读(228)  评论(0编辑  收藏  举报