Go: // Find the minimum spanning tree by the Kruskal algorithm
// -------------------------------------------------------
// Kruskal(G):
//     A = ∅
//     foreach v ∈ G.V:
//        MAKE-SET(v)
//     foreach (u, v) in G.E ordered by weight(u, v), increasing:
//         if FIND-SET(u) ≠ FIND-SET(v):
//             A = A ∪ {(u, v)}
//             UNION(u, v)
//     return A
//
// Ref: https://en.wikipedia.org/wiki/Kruskal%27s_algorithm

package main

import (
	"bufio"
	"os"
	"sort"
	"strconv"
	"strings"
	"fmt"
	)

var scanner = bufio.NewScanner(os.Stdin)
var (
	matrix [][]int
)

type Edge struct {
	a, b, cost, added int
}
type ByCost []Edge

var edges ByCost

func (a ByCost) Len() int           { return len(a) }
func (a ByCost) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByCost) Less(i, j int) bool { return a[i].cost < a[j].cost }

func main() {
	for scanner.Scan() {
		buf := strings.Split(scanner.Text(), " ")
		n, _ := strconv.Atoi(buf[0])
		m, _ := strconv.Atoi(buf[1])
		if n == 0 && m == 0 {
			break
		}
		matrix = make([][]int, n)
		for i := range matrix {
			matrix[i] = make([]int, n)
		}
		for i := 0; i < m; i++ {
			scanner.Scan()
			buf_ := strings.Split(scanner.Text(), " ")
			a, _ := strconv.Atoi(buf_[0])
			b, _ := strconv.Atoi(buf_[1])
			cost, _ := strconv.Atoi(buf_[2])
			matrix[a][b] = cost
			matrix[b][a] = cost
		}
		sum := Kruskal(n)
		fmt.Println(sum)
		if len(edges) > 0 {
			edges = []Edge{}
		}
	}
}

func Kruskal_func(size, edge_num int) int {
	for i := 0; i < size; i++ {
		for j := 0; j < size; j++ {
			if matrix[i][j] > 0 {
				tmp := Edge{i, j, matrix[i][j], 0}
				edges = append(edges, tmp)
			}
		}
	}
	sort.Sort(ByCost(edges))
	UF_Init(edge_num)
	for i := 0; i < edge_num; i++ {
		a := edges[i].a
		b := edges[i].b
		if UF_Find(a) != UF_Find(b) {
			edges[i].added = 1
			UF_Union(UF_Find(a), UF_Find(b))
		}
	}
	sum := 0
	for i := 0; i < edge_num; i++ {
		if edges[i].added != 0 {
			// log.Printf("edge(%d,%d) is added\n", edges[i].a, edges[i].b)
			sum += edges[i].cost
		}
	}
	return sum
}

func Kruskal(size int) int {
	edge_num := 0
	for i := 0; i < size; i++ {
		for j := 0; j < size; j++ {
			if matrix[i][j] > 0 {
				edge_num++
			}
		}
	}
	return Kruskal_func(size, edge_num)
}

/*** Union-Find functions ***/
var UF_Parent []int
var UF_Rank []int

func UF_Init(n int) {
	UF_Parent = make([]int, n)
	UF_Rank = make([]int, n)
	for i := 0; i < n; i++ {
		UF_Parent[i] = i
		UF_Rank[i] = 0
	}
}
func UF_Union(a, b int) {
	if UF_Rank[a] < UF_Rank[b] {
		UF_Parent[a] = b
	} else {
		UF_Parent[b] = a
	}
	if UF_Rank[a] == UF_Rank[b] {
		UF_Rank[a]++
	}
}
func UF_Find(a int) int {
	if UF_Parent[a] == a {
		return a
	}
	return UF_Find(UF_Parent[a])
}
/*** Union-Find functions ***/

C++: #include <bits/stdc++.h>
#define rep(i, n) for (ll i = 0; i < (ll)n; i++)
#define PI 3.14159265358979323846
#define vll vector<long long>
using namespace std;
using ll = long long;
using ld = long double;

class UnionFind {
private:
  ll n;
  vll P;
  ll root(ll x);
  void setN(ll N);
  void init();

public:
  UnionFind(ll N);
  void unite(ll x, ll y);
  bool same(ll x, ll y);
};

// コンストラクタ
UnionFind::UnionFind(ll N) {
  setN(N);
  init();
}

// nを変更
void UnionFind::setN(ll N) { n = N; }

// Union-Find Treeを初期化する
void UnionFind::init() {
  P.clear();
  rep(i, n) { P.push_back(i); }
}

// 根の値を返す
ll UnionFind::root(ll x) {
  if (P[x] == x) { return x; }
  return (P[x] = root(P[x])); // パス圧縮しつつ返す
}

// 木を結合する（rankはとりあえず無視）
void UnionFind::unite(ll x, ll y) { P[root(x)] = root(y); }

// xとyが同じ集合にあるか判別
bool UnionFind::same(ll x, ll y) {
  if (root(x) == root(y)) {
    return true;
  } else {
    return false;
  }
}

// ----本問について----
// 問題：橋の取り壊し
// 問題文URL：https://onlinejudge.u-aizu.ac.jp/problems/0180
// 所要時間：
// 学んだこと：
// ------------------

// ----ここから本問のソースコード----

struct edge {
  ll w, s, e; // weight, start, end

  // コンストラクタ
  edge(ll W, ll S, ll E) {
    w = W;
    s = S;
    e = E;
  }
};

// edge用の比較関数
bool cmpI(const edge &a, const edge &b) { return a.w < b.w; }

// グローバル変数（入力）
ll n, m;
vector<edge> edges;

// 入力
void input() {
  edges.clear();
  rep(i, m) {
    ll a, b, cost;
    cin >> a >> b >> cost;
    edges.push_back(edge(cost, a, b));
  }
}

// 最小全域木の重みの合計を求める（クラスカル法）．
void solve() {
  sort(edges.begin(), edges.end(), cmpI); // 辺を重みをキーに昇順ソート
  UnionFind u(n);                         // UnionFind木を初期化
  ll ans = 0;
  rep(i, edges.size()) {
    if (!u.same(edges[i].s, edges[i].e)) { // 閉路ができない
      u.unite(edges[i].s, edges[i].e);     // 辺を張る
      ans += edges[i].w;
    }
  }
  cout << ans << endl;
}

int main() {
  while (cin >> n >> m && n > 0) {
    input();
    solve();
  }
  return 0;
}

C++: #include <bits/stdc++.h>
using namespace std;

using P = pair<int, int>;

struct edge {
    int to, weight;
};

constexpr int INF = 1e9;

int main() {
    int n, m;
    while(cin >> n >> m, n) {
        vector<vector<edge>> g(n);
        for(int i=0; i<m; ++i) {
            int a, b, cost;
            cin >> a >> b >> cost;
            g[a].push_back((edge){b, cost});
            g[b].push_back((edge){a, cost});
        }

        vector<int> d(n, INF);
        vector<bool> used(n);
        d[0] = 0;
        int res = 0;
        priority_queue<P, vector<P>, greater<P>> que;
        que.push(make_pair(0, 0));
        while(!que.empty()) {
            P p = que.top();
            que.pop();
            int v = p.second;
            if(d[v] < p.first) {
                continue;
            }
            used[v] = true;
            res += d[v];
            for(auto& e : g[v]) {
                if(!used[e.to] && e.weight < d[e.to]) {
                    d[e.to] = e.weight;
                    que.push(make_pair(d[e.to], e.to));
                }
            }
        }
        cout << res << endl;
    }
}

C++: // デブンキー一家の大活躍.cpp : Defines the entry point for the console application.
//
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

bool check(bool a[], int n) {
	for (int i = 0; i < n; i++) {
		if (a[i] == false) {
			return false;
		}
	}

	return true;
}

int main(void)
{
	int result[1000], suffix = 0;

	while (1) {
		int ncity, nbridge, glaph[100][100] = { 0 };

		scanf("%d %d", &ncity, &nbridge);
		if (ncity == 0 && nbridge == 0) {
			break;
		}
		int a, b, value;
		for (int i = 0; i < nbridge; i++) {
			scanf("%d %d %d", &a, &b, &value);
			glaph[a][b] = value;
			glaph[b][a] = value;
		}

		int min, cost = 0, s;
		bool visit[100] = { false };
		visit[0] = true;

		int count = 0;
		while (check(visit, ncity) == false) {
			min = 100;
			for (int i = 0; i < ncity; i++) {
				if (visit[i] == true) { //始点
					for (int j = 0; j < ncity; j++) { //隣接点
						if (glaph[i][j] != 0 && visit[j] == false) {
							if (min > glaph[i][j]) {
								min = glaph[i][j];
								s = j;
							}
						}
					}
				}
			}

			visit[s] = true;
			cost += min;
		}

		result[suffix++] = cost;
	}

	for (int i = 0; i < suffix; i++) {
		printf("%d\n", result[i]);
	}

	return 0;
}

C++: #include<iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
int main(){
  int n,m;
  while(cin >>n>>m,n||m){
    vector<pair<int,pair<int, int> > > bridge;
    bool city[101] = {false};
    int cost = 0;
    for(int i=0; i<m; i++){
      int x,y,z;
      cin >>x>>y>>z;
      bridge.push_back(make_pair(z,make_pair(x,y)));
    }
    sort(bridge.begin(),bridge.end());
    city[bridge[0].second.first] = true;
    city[bridge[0].second.second] = true;
    cost+=bridge[0].first;
    for(int i=1; i<n; i++){
      for(int j=0; j<m; j++){
	if(city[bridge[j].second.first] && (!city[bridge[j].second.second])){
	  cost+=bridge[j].first;
	  city[bridge[j].second.second] = true;
	  break;
	}
	if((!city[bridge[j].second.first]) && city[bridge[j].second.second]){
	  cost+=bridge[j].first;
	  city[bridge[j].second.first] = true;
	  break;
	}
      }
    }
    cout <<cost<<endl;
  }
  return 0;
}