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 ***/

Python: import sys
readline = sys.stdin.readline
write = sys.stdout.write

def solve():
    N, M = map(int, readline().split())
    if N == 0:
        return False
    *p, = range(N)
    def root(x):
        if x == p[x]:
            return x
        p[x] = y = root(p[x])
        return y
    def unite(x, y):
        px = root(x); py = root(y)
        if px == py:
            return 0
        if px < py:
            p[py] = px
        else:
            p[px] = py
        return 1

    E = []
    for i in range(M):
        a, b, c = map(int, readline().split())
        E.append((c, a, b))
    E.sort()
    ans = 0
    for c, a, b in E:
        if unite(a-1, b-1):
            ans += c
    write("%d\n" % ans)
    return True
while solve():
    ...

Python: import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15

class UnionFind():
    def __init__(self,n):
        self.n = n
        self.parents = [-1]*n

    def find(self,x): #根を見つける、繋ぎ直す
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]
    
    def unite(self,x,y): #x,yの含むグループを併合する
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return
        
        if self.parents[x] > self.parents[y]:
            x,y = y,x

        self.parents[x] += self.parents[y]
        self.parents[y] = x
    
    def same(self,x,y):#xとyが同じグループにいるか判定
        return self.find(x) == self.find(y)

def solve(N,M):
    edges = [tuple(map(int,input().split())) for _ in range(M)]
    edges.sort(key = lambda x:x[2])
    uf = UnionFind(N)

    ans = 0
    for a,b,c in edges:
        if uf.same(a,b):
            continue
        else:
            uf.unite(a,b)
            ans += c
    print(ans)

def main():
    while True:
        N,M = map(int,input().split())
        if N == 0:
            return
        solve(N,M)
if __name__ == '__main__':
    main()

Python: import sys
input = sys.stdin.readline

class Unionfind:
    def __init__(self, n):
        self.par = [-1]*n
        self.rank = [1]*n
    
    def root(self, x):
        r = x
        
        while not self.par[r]<0:
            r = self.par[r]
        
        t = x
        
        while t!=r:
            tmp = t
            t = self.par[t]
            self.par[tmp] = r
        
        return r
    
    def unite(self, x, y):
        rx = self.root(x)
        ry = self.root(y)
        
        if rx==ry:
            return
        
        if self.rank[rx]<=self.rank[ry]:
            self.par[ry] += self.par[rx]
            self.par[rx] = ry
            
            if self.rank[rx]==self.rank[ry]:
                self.rank[ry] += 1
        else:
            self.par[rx] += self.par[ry]
            self.par[ry] = rx
    
    def is_same(self, x, y):
        return self.root(x)==self.root(y)
    
    def count(self, x):
        return -self.par[self.root(x)]

while True:
    n, m = map(int, input().split())
    
    if n==0 and m==0:
        exit()
        
    edges = [tuple(map(int, input().split())) for _ in range(m)]
    edges.sort(key=lambda t: t[2])
    uf = Unionfind(n)
    ans = 0
    
    for a, b, c in edges:
        if not uf.is_same(a, b):
            uf.unite(a, b)
            ans += c
    
    print(ans)

Python: # AOJ 0180 Demolition of Bridges
# Python3 2018.6.22

# UNION-FIND library
class UnionSet:
	def __init__(self, nmax):
		self.size = [1]*nmax
		self.id = [i for i in range(nmax+1)]
	def root(self, i):
		while i != self.id[i]:
			self.id[i] = self.id[self.id[i]]
			i = self.id[i]
		return i
	def connected(self, p, q): return self.root(p) == self.root(q)
	def unite(self, p, q):
		i, j = self.root(p), self.root(q)
		if i == j: return
		if self.size[i] < self.size[j]:
			self.id[i] = j
			self.size[j] += self.size[i]
		else:
			self.id[j] = i
			self.size[i] += self.size[j]
# UNION-FIND library

# 最小全域木。V:総ノード数、E:枝情報(a,b,cost)
def kruskal(V, edge):
	edge2 = sorted(edge, key=lambda x:(x[2]))
	u = UnionSet(V)
	ans = 0
	for e in edge2:
		if not u.connected(e[0], e[1]):
			u.unite(e[0], e[1])
			ans += e[2]
	return ans;

while 1:
	n, m = map(int, input().split())
	if n == 0: break
	edge = []
	for i in range(m):
		s, t, w = map(int, input().split())
		edge.append((s, t, w))
	print(kruskal(n, edge))

Python: from heapq import heappush, heappop

def get_par(x, par_lst):
  if x == par_lst[x]:
    return x
  p = get_par(par_lst[x], par_lst)
  par_lst[x] = p
  return p

while True:
  n, m = map(int, input().split())
  if n == 0:
    break
  que = []
  for _ in range(m):
    a, b, c = map(int, input().split())
    heappush(que, (c, a, b))
  
  par_lst = [i for i in range(n)]
  ans = 0
  while que:
    c, a, b = heappop(que)
    pa, pb = get_par(a, par_lst), get_par(b, par_lst)
    if pa != pb:
      par_lst[pa] = pb
      ans += c
  print(ans)