Go: package main

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

func getScanner(fp *os.File) *bufio.Scanner {
	scanner := bufio.NewScanner(fp)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 500001), 500000)
	return scanner
}

func getNextString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}

func main() {
	fp := os.Stdin
	if len(os.Args) > 1 {
		fp, _ = os.Open(os.Args[1])
	}

	scanner := getScanner(fp)
	writer := bufio.NewWriter(os.Stdout)

	n := getNextInt(scanner)

	g := make([][]int, n)
	ans := make([][]int, n)

	inf := 1 << 30
	for i := 0; i < n; i++ {
		g[i] = make([]int, n)
		ans[i] = make([]int, n)
		for ii := 0; ii < n; ii++ {
			g[i][ii] = getNextInt(scanner)
			if g[i][ii] == -1 {
				g[i][ii] = inf
			}
			ans[i][ii] = -1
		}
	}

	im := make(IntMap, 1)

	im.increment(1)

	for len(im) < n {
		min := inf
		u := -1
		v := -1
		for i := range im {
			for ii := 0; ii < n; ii++ {
				if im.get(ii) != 0 {
					continue
				}
				if min > g[i][ii] {
					min = g[i][ii]
					u = i
					v = ii
				}
			}
		}
		im.increment(v)
		ans[u][v] = min
		ans[v][u] = min
	}

	sum := 0
	for i := 0; i < n-1; i++ {
		for ii := i + 1; ii < n; ii++ {
			if ans[i][ii] != -1 {
				sum += ans[i][ii]
			}
		}
	}

	fmt.Fprintln(writer, sum)
	writer.Flush()
}

// IntMap ...
type IntMap map[int]int

func (m IntMap) get(key int) int {
	if _, ok := m[key]; ok {
		return m[key]
	}
	return 0
}
func (m IntMap) increment(key int) {
	if _, ok := m[key]; ok == false {
		m[key] = 0
	}
	m[key]++
}

Python: import itertools

n = int(input())
A = []
for i in range(n):
    line = input()
    A.append([int(x) for x in line.split()])


V = set(range(n))
Vnew = {0}  # ??¨???????°???¨?????????
weights = []

while V != Vnew:
    T = V - Vnew
    minw = float('inf')
    for u, v in itertools.product(Vnew, T):
        w = A[u][v]
        if w != -1 and minw > w:
            e = (u, v)
            minw = w
    Vnew.add(e[1])
    weights.append(minw)

print(sum(weights))

Python: N = 100

n = int(input())
adj = [[0 for i in range(n)] for j in range(n)]

for i in range(n):
    tmp = list(map(int, input().split()))
    u = tmp[0]
    u = u -1
    k = tmp[1]
    v = tmp[2:] -1
    for j in range(k):
        adj[u][v[j]] = 1
        
for i in range(n):
        print(" ".join(list(map(str, adj[i]))))

Python: def root(x):
    path_to_root = []
    while x != P[x]:
        path_to_root.append(x)
        x = P[x]
    for node in path_to_root:
        P[node]=x
    return x

def unite(x,y):
    P[root(x)] = root(y)

def is_same_set(x,y):
    return root(x) == root(y)

n = int(input())
P = [i for i in range(n)]
length=[]
points=[]
for i in range(n):
    length.append(list(map(int,input().split())))
for i in range(n):
    for j in range(i,n):
        if length[i][j] != -1:
            points.append((i,j,length[i][j]))
	
points.sort(key=lambda x:x[2])

totalweight = 0
for p in points:
    i,j,w = p
    if not is_same_set(i,j):
       totalweight += w
       unite(i,j)

print(totalweight)

Python: n = int(input())
A = [[int(i) for i in input().strip().split(" ")] for j in range(n)]

dp1={}

for i in range(n):
    for j in range(n):
        if A[i][j] != -1 :
            dp1[(i,j)] = A[i][j]
key = []
value = []
for i,j in sorted(dp1.items(), key=lambda x:x[1]):
    key.append(i)
    value.append(j)

c_v = []
N = len(key)
len_c_v = 0
ans = 0
itr = 0
while itr != N:
    if len_c_v == n:
        break
    i = key[itr][0]
    j = key[itr][1]
    if (i in c_v) == False and (j in c_v) == False:
        c_v.append(i)
        c_v.append(j)
        ans += value[itr]
        len_c_v += 2
        itr += 1
    elif (i in c_v) == False:
        c_v.append(i)
        ans += value[itr]
        itr += 1
        len_c_v += 1
    elif (j in c_v) == False:
        c_v.append(j)
        ans += value[itr]
        itr += 1
        len_c_v += 1
    else:
        itr += 1


if len_c_v != n:
    print(-1)
else:
    print(ans)

Python: n = int(input())
a = []

for i in range(n):
    inp = input()
    if "-1" in inp:
        inp = inp.replace("-1","10000")
    a.append(list(map(int, inp.split())))

w = 0
v = set()
v.add(0)

while len(v) < n:
    min_w   = 10000
    min_idx = 0
    i = 0
    for node in v:
        if min_w > min(a[node]):
            min_w = min(a[node])
            i = node
            min_idx = a[i].index(min_w)
    if min_idx in v:
        a[i][min_idx] = 10000
        continue
    else:
        w += min_w
        v.add(min_idx)

print(w)

Python: import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline

class union_find():
    
    def __init__(self,n):
        self.n=n
        self.root=[-1]*(n+1)
        self.rank=[0]*(n+1)

    def find_root(self,x):
        if self.root[x]<0:
            return x
        else:
            self.root[x]=self.find_root(self.root[x])
            return self.root[x]

    def unite(self,x,y):
        x=self.find_root(x)
        y=self.find_root(y)

        if x==y:
            return 
        elif self.rank[x]>self.rank[y]:
            self.root[x]+=self.root[y]
            self.root[y]=x
        else:
            self.root[y]+=self.root[x]
            self.root[x]=y

            if self.rank[x]==self.rank[y]:
                self.rank[y]+=1

    def same(self,x,y):
        return self.find_root(x)==self.find_root(y)

    def cnt(self,x):
        return -self.root[self.find_root(x)]

n=int(input().rstrip())
G=union_find(n)
g=[]
for k in range(n):
    a=[int(i) for i in input().split()]
    for j in range(n):
        if a[j]!=-1:
            g.append((k,j,a[j]))
g.sort(key=lambda x:x[2])
ans=0
for i in g:
    u,v,c=i
    if not G.same(u,v):
        G.unite(u,v)
        ans+=c
print(ans)

Python: from heapq import heappush, heappop

def search(v, u):
    while v != root[v]: v = root[v]
    while u != root[u]: u = root[u]
    
    return v, u

def rebuild(v, u, r):
    while v != root[v]: v, root[v] = root[v], r
    while u != root[u]: u, root[u] = root[u], r
    return v, u

n = int(input())
root = [i for i in range(n)]
depth = [1] * n

q = []

for i in range(n):
    for j, c in enumerate(list(map(int, input().split()))):
        if c == -1: continue
        heappush(q, (c, i, j))
        
ans = 0

while q:
    c, v, u = heappop(q)
    
    v_r, u_r = search(v, u)
    if v_r == u_r: continue
    
    ans += c
    
    v_d, u_d = depth[v_r], depth[u_r]
    if v_d == u_d:
        depth[v_r] += 1
        if depth[v_r] > 10: rebuild(v, u, v_r)
        
    elif v_d < u_d: v_r, u_r = u_r, v_r
    
    root[v_r] = u_r
    
print(ans)

Python: class Forest:
    def __init__(self, g, id):
        self.forest = set([id])
        self.graph = g
        self.next_wait = self.graph[id]
        self.wait = 0
    def add_tree(self, id):
        self.wait += self.next_wait[id]
        self.forest.update([id])
         
        self.marge_next_wait(id)
    def next_tree(self):
        min_id = min_wait = None
        for id, wait in self.next_wait.items():
            if id not in self.forest:
                if min_wait == None or min_wait > wait:
                    min_wait = wait
                    min_id = id
        return min_id
    def marge_next_wait(self, merge_id):
        for id, wait in self.graph[merge_id].items():
            if id not in self.next_wait or self.next_wait[id] > wait:
                self.next_wait[id] = wait
n = int(input())
g = [{e:i for e, i in enumerate(map(int, input().split())) if i != -1} for _ in range(n)]
forest = Forest(g,0)
for i in range(n - 1):
    id = forest.next_tree()
    forest.add_tree(id)
print(forest.wait)