Luo Gu [template] minimum spanning tree

Copyright: blogger original, welcome to reprint. Please indicate the source https://blog.csdn.net/baidu_41248654/article/details/78883588

Topic links: https://www.luogu.org/problemnew/show/P3366
here not explain

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cstdlib>
using namespace std;
int n,m,fa[5010],ans=0,flag=0;
struct node
{
    int u,v,c;
} p[200010];
int get(int a)
{
    if(a==fa[a])
        return a;
    else
        return fa[a]=get(fa[a]);
}
bool cmp(node ar,node br)
{
    return ar.c<br.c;
}
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].u,&p[i].v,&p[i].c);
    sort(p+1,p+1+m,cmp);
    for(int i=1; i<=m; i++)
    {
        int x=p[i].u,y=p[i].v;
        int fx=get(x),fy=get(y);
        if(fx!=fy)
        {
            ans+=p[i].c;
            fa[fx]=fy;
        }
    }
    for(int i=1; i<=n; i++)
    {
        if(fa[i]==i)
        {
            flag++;
            if(flag==2)
                break;
        }
    }
    if(flag==2)
        printf("orz");
    else
        printf("%d",ans);
    return 0;
}

Guess you like

Origin blog.csdn.net/baidu_41248654/article/details/78883588