51nod1212【最小生成树kruskal算法】

思路:

利用破圈法。

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;

const int N=1e3+10;

struct asd{
    int x,y;
    int w;
};
asd q[N*50];
int tol;
int pre[N];

bool cmp(asd a,asd b)
{
    return a.w<b.w;
}

int Find(int x)
{
    int r=x;
    while(pre[r]!=r)
        r=pre[r];
    int i=x,j;
    while(pre[i]!=r)
    {
        j=pre[i];
        pre[i]=r;
        i=j;
    }
    return r;
}


int main()
{
    int n,m;
    int a,b,c;
    scanf("%d%d",&n,&m);
    tol=0;
    while(m--)
    {
        scanf("%d%d%d",&q[tol].x,&q[tol].y,&q[tol].w);
        tol++;
    }
    sort(q,q+tol,cmp);
    for(int i=1;i<=n;i++)
        pre[i]=i;
    int ans=0;
    for(int i=0;i<tol;i++)
    {
        int aa=Find(q[i].x);
        int bb=Find(q[i].y);
        if(aa!=bb)
        {
            ans+=q[i].w;
            pre[aa]=bb;
        }
    }
    printf("%d
",ans);
    return 0;
}




原文地址:https://www.cnblogs.com/keyboarder-zsq/p/6216810.html