洛谷P1111 修复公路 并查集

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

这题就是并查集的运用,我们先将每条道路按完工时间由小到大排序。我们每次从未完工的挑一条时间最少的,把它完工,看他的起点和终点是否未曾相连(即是不是一个连通块),将他们相连,并将连通块边数cnt++,当连通块连通了所有点(即cnt==n-1),输出此时的时间。如果公路全部建完,还没满足条件,输出-1。
代码如下

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e3+5;
const int maxm=1e5+5;
struct node
{
    int from,to,value;
}p[maxm];
bool cmp(node a,node b)
{
    return a.value<b.value;
}
int fa[maxn];
int find(int x)
{
    if(x==fa[x])
    return x;
    return fa[x]=find(fa[x]);
}
int n,m;
int main()
{
    scanf("%d %d",&n,&m);
    for(int i=1;i<=n;i++)
    fa[i]=i;
    for(int i=1;i<=m;i++)
    {
        scanf("%d %d %d",&p[i].from,&p[i].to,&p[i].value);
    }
    sort(p+1,p+1+m,cmp);
    int cnt=0;
    for(int i=1;i<=m;i++)
    {
        int x=p[i].from,y=p[i].to,c=p[i].value;
        int xx=find(x),yy=find(y);
        if(xx!=yy)
        fa[xx]=yy,cnt++;
        if(cnt==n-1)
        {
            printf("%d\n",c);
            return 0;
        }
    }
    puts("-1");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44491423/article/details/104497577