修复公路(并查集)

题目链接:https://www.luogu.com.cn/problem/P1111

题意:

有n个村,给你m个信息,1个信息包含存在道路的两个村子以及通路的时间,让你求是否每个村子都能相连,若能相连输出通路最短时间

思路:

并查集+排序
一个集合中的村子能够相互连通,所以就看本来并查集n个独立的集合能不能通过所给操作union成一个共同的集合
由于要查询最短时间,所以按时间排序

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
struct node{
int x;
int y;
int t;
};
const int maxn=1e5+5;
int n,m;
int cnt;
node arr[maxn];
bool cmp(node a,node b)
{
return a.t<b.t;
}
int father[maxn];
void build()
{
for(int i=1;i<=n;i++)father[i]=i;
}
int find(int x)
{
if(x!=father[x])
{
father[x]=find(father[x]);
}
return father[x];
}
void merge(int x,int y)
{
if(find(x)!=find(y)){
father[find(x)]=find(y);
cnt--;
}
}
signed main()
{
ios::sync_with_stdio(false),cin.tie(0);
cin>>n>>m;
cnt=n;
for(int i=1;i<=m;i++)
{
cin>>arr[i].x>>arr[i].y>>arr[i].t;
}
sort(arr+1,arr+1+m,cmp);
build();
for(int i=1;i<=m;i++)
{
merge(arr[i].x,arr[i].y);
if(cnt==1){
cout<<arr[i].t;
return 0;
}
}
cout<<-1;
return 0;
}
posted @   Marinaco  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
//雪花飘落效果
点击右上角即可分享
微信分享提示