Problem:
Minimum Spanning Tree

Find the sum of weights of edges of the Minimum Spanning Tree for a given weighted undirected graph G = (V, E).

Input

|V| |E|
s0 t0 w0
s1 t1 w1
:
s|E|-1 t|E|-1 w|E|-1

, where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.

si and ti represent source and target verticess of i-th edge (undirected) and wi represents the weight of the i-th edge.

Output

Print the sum of the weights of the Minimum Spanning Tree.

Constraints

1 ≤ |V| ≤ 10,000

0 ≤ |E| ≤ 100,000

0 ≤ wi ≤ 10,000

The graph is connected

There are no parallel edges

There are no self-loops

Sample Input 1

4 6
0 1 2
1 2 1
2 3 1
3 0 1
0 2 3
1 3 5

Sample Output 1

3

Sample Input 2

6 9
0 1 1
0 2 3
1 2 1
1 3 7
2 4 1
1 4 3
3 4 1
3 5 1
4 5 6

Sample Output 2

5

Solution in C (judge verdict: Accepted)

#include <stdio.h>
#include <stdlib.h>

#define MAX_E 100000

typedef struct edge{
    int s;
    int t;
    int w;
} edge;

int *p;
int *rank;
int V,E; // V:頂点, E:辺
edge es[MAX_E];

void unite(int, int);
void init(int);
void link(int, int);
int findSet(int);
int Same(int, int);
int comp(const void *, const void *);
int kuruskal(void);

int main(){
    int s,t,w;
    int i;
    int c=0;
    edge e;
    int res;

    scanf("%d %d", &V, &E);

    for(i=0;i<E;i++){
        scanf("%d %d %d", &s,&t,&w);
        e.s=s;
        e.t=t;
        e.w=w;
        es[c++]=e;
    }

    // クラスカル法で最小全域木を計算
    res=kuruskal();

    printf("%d\n",res);

    return 0;
}

// 初期化
void init(int n){
    int i;

    // create S
    p = (int *)malloc(n*sizeof(int));
    rank = (int *)malloc(n*sizeof(int));

    // make Set
    for(i=0;i<n;i++){
        p[i] = i;
        rank[i]=0;
    }
}

// xとyの属する集合を併合
void unite(int x, int y){
    link(findSet(x),findSet(y));
}

// xとyの属する集合を併合
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]=rank[x]+1;
    }
}

// 木のrootを求める
int findSet(int x){
    if(x!=p[x]) p[x]=findSet(p[x]);
    return p[x];
}

// xとyが同じ集合に属するか否か
int Same(int x, int y){
    if(findSet(x)==findSet(y)) return 1;
    else return 0;
}

// compare
int comp(const void * e1, const void * e2){
    return ((const edge*)e1)->w - ((const edge*)e2)->w;
}

// クラスカル法
int kuruskal(void){
    int res;
    int i;
    edge e;

    qsort(es,E,sizeof(es[0]),comp); // edge.wの小さい順

    init(V); // Union-Findの初期化

    res=0; // 答え, 辺の重みの総和

    for(i=0;i<E;i++){
        e=es[i];
        if(Same(e.s,e.t)==0){
            unite(e.s,e.t);
            res+=e.w;
        }
    }

    return res;
}