当前位置:网站首页>P1111 修复公路(并查集)
P1111 修复公路(并查集)
2022-07-21 05:16:00 【Eloi0424】
个人博客:Eloi-还在前进.
P1111 修复公路(并查集)
题目来源:洛谷P1111 修复公路
题目描述:
A地区在地震过后,连接所有村庄的公路都造成了损坏而无法通车。政府派人修复这些公路。
给出A地区的村庄数NN,和公路数MM,公路是双向的。并告诉你每条公路的连着哪两个村庄,并告诉你什么时候能修完这条公路。问最早什么时候任意两个村庄能够通车,即最早什么时候任意两条村庄都存在至少一条修复完成的道路(可以由多条公路连成一条道路)
解题思路:
并查集模板题。
题意抽象化就是动态合并的连通块何时成为一个完整的连通块。
读入数据,按时间顺序sort一下。
遍历road
判断两城市是否是处于同一连通块:
不是则合并两连通块。
最终当连通块数目减为一时输出当前花费时间。
#include <bits/stdc++.h>
using namespace std;
int father[1005];
struct road
{
int x;
int y;
int t;
}r[100005];
int cmp(road x,road y)
{
return x.t<y.t;
}
int find(int x)
{
if(father[x]==x) return x;
else return find(father[x]);
}
void union_set(int x,int y)
{
int fx=find(x);
int fy=find(y);
father[fy]=fx;
}
int main()
{
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++)
{
father[i]=i;
}
for(int i=1;i<=m;i++)
{
cin>>r[i].x>>r[i].y>>r[i].t;
}
sort(r+1,r+1+m,cmp);
for(int i=1;i<=m;i++)
{
if(find(r[i].x)!=find(r[i].y))
{
union_set(r[i].x,r[i].y);
n--;
}
if(n==1)
{
cout<<r[i].t;
return 0;
}
}
cout<<"-1";
return 0;
}
边栏推荐
猜你喜欢
随机推荐
Characteristics and differences between PCB and integrated circuit
Explain the principle, classification and function of microphone array in detail
「跑象科技」获得天使+融资,打造新一代实时数据基础平台
1046. Weight of the last stone
437. 路径总和 III
Let you know the current situation and future development trend of wireless charging technology
Programmation créative / groupe primaire (4e - 6e année) - graphisme créatif
Deep analysis of fiboracci sequence
What is an electronic scale weighing module? What functions does it have?
14. 最长公共前缀
04 unittest unit test framework
数据可视化图表插件开发作品大赏(一)
Analysis of the characteristics of matter protocol (I) support non matter protocol, private protocol, and technical analysis of matter Bridge
Do you really understand the 01 backpack problem? Can you answer these questions of 01 backpack?
299. Guessing numbers game
148. 排序链表
Concurrency opening -- take you from 0 to 1 to build the cornerstone of concurrency knowledge system
06 page object + pytest unit test framework
2021普及组总结
2020普及组总结