Networking-- template minimum spanning tree problem

Topic Link

Meaning of the questions:

M n points you find the right edges of the minimum spanning tree

answer:

Minimum spanning tree bare board

 

Code:

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
const int maxn = 50;
int f[maxn];
int n,cnt;
struct node
{
    int u,v,w;
    bool operator < (const node &a)const
    {
        return w<a.w;
    }
} edge[maxn*maxn];

int Find(int x)
{
    return x==f[x]?x:f[x]=Find(f[x]);
}
int kruskal()
{
    int ans=0;
    for(int i=0; i<=n; i++)f[i]=i;
    int sum=0;
    sort(edge,edge+cnt);
    for(int i=0; i<cnt; i++)
    {
        int x=edge[i].u;
        int y=edge[i].v;
        int fx=Find(x);
        int fy=Find(y);
        if(fx!=fy)
        {
            f[fx]=fy;
            ans+=edge[i].w;
            sum++;
        }
        if(sum==n-1)break;
    }
    return ans;
}
int main()
{
    int n,m;
    while(~scanf("%d%d",&n,&m) && n)
    {
        cnt=m;
        for(int i=0;i<=n;i++)f[i]=i;
        for(int i=0;i<m;i++)
        {
            int u,v,w;
            scanf("%d%d%d",&u,&v,&w);
            edge[i].u=u;
            edge[i].v=v;
            edge[i].w=w;
        }
        printf("%d\n",kruskal());

    }
    return 0;
}
kruskal

 

Guess you like

Origin www.cnblogs.com/j666/p/11616873.html