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++14 (judge verdict: Memory Limit Exceeded)

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
typedef long long  ll;
#define rep(i,s,n)for(ll i=s;i<n;i++)
#define repe(i,s,n)for(ll i=s;i<=n;i++)

static const ll MOD = 1e9 + 7;
static const ll INF = (ll)1 << 62;

static const ll MAX_N = 100001;
static const ll MAX_M = 100001;

ll V;
ll d[MAX_N] = {};
struct edge { ll to, cost; };
typedef pair<ll, ll> P;
vector<edge> G[MAX_N];
priority_queue <P, vector<P>, greater<P>> que;
bool mst[MAX_N];
//
//void dijkstra(ll s) {
//	fill(d, d + V, INF);
//	fill(mst, mst + V, false);
//
//	d[s] = 0;
//	que.push(P(0, s));
//
//	while (!que.empty()) {
//		P p = que.top(); que.pop();
//		ll v = p.second;
//		if (d[v] < p.first)continue;
//		rep(i, 0, G[v].size()) {
//			edge e = G[v][i];
//			if (!mst[e.to] && d[e.to] > d[v] + e.cost) {
//				d[e.to] = d[v] + e.cost;
//				que.push(P(d[e.to], e.to));
//			}
//		}
//	}
//}
ll cost = 0;
void prim(ll s) {
	fill(d, d + V, INF);
	d[s] = 0;
	que.push(P(0, s));

	while (!que.empty()) {
		P p = que.top(); que.pop();
		ll v = p.second;

		cost += p.first;
		mst[v] = true;

		bool complete = true;
		rep(i, 0, G[v].size()) {
			edge e = G[v][i];
			if (!mst[e.to]) {// && d[e.to] > d[v] + e.cost) {
				d[e.to] = d[v] + e.cost;
				que.push(P(e.cost, e.to));
				complete = false;
			}
		}
		if (complete)break;
	}
}

int main() {
	ll E; cin >> V >> E;
	rep(i, 0, E) {
		ll s, t, d; cin >> s >> t >> d;
		G[s].push_back(edge{ t,d });
		G[t].push_back(edge{ s,d });
	}

	//dijkstra(r);
	prim(0);

	cout << cost << endl;

	return 0;
}