修复公路(并查集)

题目链接: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 @ 2025-01-04 13:12  Marinaco  阅读(25)  评论(0)    收藏  举报
//雪花飘落效果