洛谷 P1111 修复公路(最小生成树)

传送门


Kruskal裸题嘻嘻
不说了
Code:

#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;

struct node{
    int x,y,c;
    inline bool operator <(const node &b)const
    {
        return c<b.c;
    }
}a[100010];
int n,m,f[1010];

inline int findfa(int x)
{
    if(f[x]==x) return x;
    return f[x]=findfa(f[x]);
}

int main()
{
    scanf("%d %d",&n,&m);
    for(int i=1;i<=m;i++)
        scanf("%d %d %d",&a[i].x,&a[i].y,&a[i].c);
    sort(a+1,a+1+m);
    int tot=0,ans=0;
    for(int i=1;i<=n;i++) f[i]=i;
    for(int i=1;i<=m;i++)
    {
        int fx=findfa(a[i].x),fy=findfa(a[i].y);
        if(fx!=fy)
        {
            f[fx]=fy;
            tot++;
            ans=max(ans,a[i].c);
        }
        if(tot==n-1) break;
    }
    if(tot<n-1) printf("-1");
    else printf("%d",ans);
}

猜你喜欢

转载自blog.csdn.net/Dawn_LLLLLLL/article/details/80043412