Kruskal

#include <iostream>
#include <set>
#include <map>
#include <vector>
#include <algorithm>
#include <string>
#include <utility>
#include <functional>
#include <stack>
#include <queue>
#include <deque>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include<fstream>
using namespace std;
#define siz 100005
typedef long long ll;

int N,E,rank[siz],p[siz];

struct edge{
    int u,v,weight;
};

edge EDGE[siz];

void Make_set(int x)
{
    rank[x]=0;
    p[x]=x;
}

void LINK(int x, int y)
{
    if(rank[x]>rank[y]) p[y]=x;
    else
    {
        p[x]=y;
        if(rank[x]==rank[y]) rank[y]+=1;
    }
}
int Find_set(int x)
{
    if(p[x]!=x) return p[x]=Find_set(p[x]);
    return p[x];
}

void Union(int x, int y)
{
    LINK(Find_set(x), Find_set(y));
}

bool operator<(edge a, edge b)
{
    if(a.weight!=b.weight) return a.weight<b.weight;
    return false;
}

int main()
{
    while(scanf("%d%d",&N,&E))
    {
        for(int i=0;i<=N;i++) Make_set(i);
        for(int i=0;i<E;i++)
        {
            int a,b,c;
            scanf("%d%d%d",&a,&b,&c);
            EDGE[i].u=a;
            EDGE[i].v=b;
            EDGE[i].weight=c;
        }

        sort(EDGE, EDGE+N);
        ll value=0;

        for(int i=0;i<N;i++)
        {
            if(Find_set(EDGE[i].u)!=Find_set(EDGE[i].v))
            {
                value+=EDGE[i].weight;
                Union(EDGE[i].u, EDGE[i].v);
            }
        }

        printf("%lld\n",value);
    }
    return 0;
}

No comments:

Post a Comment