P1396 营救

编程入门 行业动态 更新时间:2024-10-10 23:25:24

P1396 营救

P1396 营救

luogu

解法:Kruskal最小生成树;
在构建最小生成树时,如果 s 与 t 在一个集合里时,当前边就是答案(因为便是按照升序排的)

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<vector>
using namespace std;
struct H{int x,y;int cost;
}a[20009];
int f[20009];
int find(int x)
{if(f[x]==x) return x;return f[x]=find(f[x]);
}
int s,t,n,m,ans;
int my_comp(const H&a,const H&b)
{if(a.cost<b.cost) return 1;return 0;
}
int main()
{scanf("%d%d%d%d",&n,&m,&s,&t);for(int i=1;i<=m;i++){int x,y,z;scanf("%d%d%d",&x,&y,&z);a[i].x=x,a[i].y=y,a[i].cost=z;}   for(int i=1;i<=n;i++) f[i]=i;sort(a+1,a+m+1,my_comp);for(int p=1;p<=m;p++){int c=find(a[p].x),b=find(a[p].y);f[c]=b;  if(find(s)==find(t)) {ans=a[p].cost;break;  }}printf("%d",ans);return 0;
} 

更多推荐

P1396 营救

本文发布于:2024-02-13 15:03:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1758989.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!