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: Memory Limit Exceeded)

#include<stdio.h>
#include<stdlib.h>
#define LARGE 10000
#define INF 100000000
#define MIN(a,b) ((a) < (b) ? (a):(b))

int **a;
int V,E;

typedef struct node{
	int id;
	int cost;
}node;

void swap(node h[],int x,int y){
	node temp=h[x];
	h[x]=h[y];
	h[y]=temp;
	return;
}


void heapsort(node heap[],int num){

	for(int i=num-1;i>0;i--){
		if(i%2==0){
			if(heap[i].cost < heap[i/2-1].cost)swap(heap,i,i/2-1);
		}else {
			if(heap[i].cost < heap[i/2].cost)swap(heap,i,i/2);
		}
	}
	
	return;

}

int update_heap(node heap[],int num){
	int u=heap[0].id;
	swap(heap,0,num-1);
	num--;
	
	for(int i=0;i<num;i++){
		heap[i].cost=MIN(heap[i].cost,a[u][heap[i].id]);
	}
	
	return num;
}


int main(){
	int i,j;
	int s,t,d;
	int num=0;
	int ans=0;
	node heap[LARGE];
	
	scanf("%d %d",&V,&E);
	
	a=malloc(sizeof(int *)*V);
	for(i=0;i<V;i++){
		a[i]=malloc(sizeof(int)*V);
		for(j=0;j<V;j++){
			a[i][j]=INF;
		}
	}
	
	for(i=0;i<E;i++){
		scanf("%d %d %d",&s,&t,&d);
		a[s][t]=d;
		a[t][s]=d;
	}
	
	for(i=1;i<V;i++){
		heap[num].cost=a[0][i];
		heap[num++].id=i;
	}
	
	heapsort(heap,num);
	
	while(num!=0){
		ans+=heap[0].cost;
		num=update_heap(heap,num);
		heapsort(heap,num);
	}
	
	printf("%d\n",ans);
	
	return 0;
	
}