知识点:并查集 结构体 sort排序
题目洛谷链接:https://www.luogu.com.cn/problem/P1111
题概要:给出n个城市m条路,若任意两个城市不相连则输出-1,反之输出两城市建造用时所需最少时间。
思路来源:https://pengqwq.blog.luogu.org/solution-p1111
知识铺垫
sort/cmp的运用
sort:
sort使用需添加头文件#include<algorithm>,也可直接用万能头文件#include<bits/stdc++.h>
sort内置快排模板,采取左闭右开原则
例:sort( a ,a+5,cmp)
从 a + 0 到 a + 4数据
cmp:
目前学习主要运用于结构体排序定义
struct CR
{
int x, y, t;
}a[100000];
int fa[100000];
int cmp(CR a1, CR a2)
{
return a1.t < a2.t;
}
return返回的可形象地理解为 a1.t 比 a2.t 小,即升序排列
同样a1.t > a2.t 理解为a1.t 比 a2.t 大,即降序排列
思路分析
- 先将所有城市道路的链接存入结构体
- 对结构体进行升序排列(方便后面判断已经所有城市全联通后输出最小的时间
- 并查集基本操作:初始化,查询,合并,路径优化
- 每一次并查集后进行判断如果全联通直接跳出循环不再执行后续多余成环的操作,并输出当前结构体存入的时间,即最少时间
- 当全部遍历,发现集合有>1个根节点,则说明未全部链接返回-1
具体代码如下:
#include<bits/stdc++.h>
#include<algorithm>
using namespace std;
int n, m;
struct CR
{
int x, y, t;
}a[100000];
int fa[100000];
int cmp(CR a1, CR a2)
{
return a1.t < a2.t;
}
int Find(int x)
{
if (x == fa[x])
return x;
else if (fa[x] != x)
fa[x] = Find(fa[x]);
return fa[x];
}
void Union(int x1,int y1)
{
int a1 = Find(x1);
int a2 = Find(y1);
if (a1 != a2)
fa[a1] = a2;
}
int pd()
{
int ans = 0;
for (int i = 1; i <= n; i++)
{
if (fa[i] == i)
ans++;
}
if (ans == 1)
return 1;
else
return 0;
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
fa[i] = i;
}
for (int i = 1; i<=m; i ++)
{
cin >> a[i].x >> a[i].y >> a[i].t;
}
sort(a + 1, a + m + 1, cmp);
for (int i = 1; i<=m;i++)
{
Union(a[i].x, a[i].y);
if (pd())
{
cout << a[i].t;
return 0;
}
}
cout << -1;
return 0;
}