洛谷 P1396 营救

题目传送门

解题思路:

跑Kruskal,直到s与t联通,输出最大值

AC代码:

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<algorithm>
 4 
 5 using namespace std;
 6 
 7 int n,m,s,t,fa[10001],ans;
 8 struct kkk {
 9     int from,to,v;
10 }e[20001];
11 
12 bool cmp(kkk a,kkk b) {
13     return a.v < b.v;
14 }
15 
16 int find_father(int x) {
17     if(fa[x] == x) return x;
18     return fa[x] = find_father(fa[x]);
19 }
20 
21 int main()
22 {
23     scanf("%d%d%d%d",&n,&m,&s,&t);
24     for(int i = 1;i <= n; i++)
25         fa[i] = i;
26     for(int i = 1;i <= m; i++) 
27         scanf("%d%d%d",&e[i].from,&e[i].to,&e[i].v);
28     sort(e+1,e+m+1,cmp);
29     for(int i = 1;i <= m; i++) {
30         int x1 = find_father(e[i].from);
31         int y1 = find_father(e[i].to);
32         if(x1 != y1) {
33             fa[x1] = y1;
34             ans = max(ans,e[i].v);
35         }
36         if(find_father(s) == find_father(t)) {
37             printf("%d",ans);
38             return 0;
39         }
40     }
41     return 0;
42 }

 

posted @ 2019-08-06 16:50  Mr^Simon  阅读(123)  评论(0编辑  收藏  举报