Go: package main

import (
	"fmt"
	"sort"
)

type Edge struct {
	I int
	J int
	A int
}

func main() {
	var n int
	fmt.Scan(&n)

	g := make([][]int, n)
	edges := make([]Edge, 0, n*(n-1)/2)
	parents := make([]int, n)
	for i := 0; i < n; i++ {
		g[i] = make([]int, n)
		for j := 0; j < n; j++ {
			fmt.Scan(&g[i][j])
			if g[i][j] > 0 {
				edges = append(edges, Edge{i, j, g[i][j]})
			}
		}
		parents[i] = i
	}
	sort.SliceStable(edges, func(i, j int) bool { return edges[i].A > edges[j].A })

	sum := 0
	for len(edges) > 0 {
		edge := edges[len(edges)-1]
		edges = edges[:len(edges)-1]

		if same(edge.I, edge.J, &parents) {
			continue
		}
		union(edge.I, edge.J, &parents)
		sum += edge.A
	}
	fmt.Println(sum)
}



func root(id int, parents *[]int) int {
	if id == (*parents)[id] {
		return id
	}
	return root((*parents)[id], parents)
}

func union(i, j int, parents *[]int) {
	(*parents)[root(j, parents)] = (*parents)[root(i, parents)]
}

func same(i, j int, parents *[]int) bool {
	return root(i, parents) == root(j, parents)
}

Python: import sys, collections
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = 10**10
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

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 = 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):
        return self.find(x) == self.find(y)

def kruskal(es, V):
    es.sort(key=lambda x:x[2])
    uf = UnionFind(V)
    res = 0
    for e in es:
        if not uf.same(e[0], e[1]):
            uf.unite(e[0], e[1])
            res += e[2]
    return res

def resolve():
    n = I()
    es = []
    for i in range(n):
        a = LI()
        for j in range(n):
            if a[j]!=-1:
                es.append((i, j, a[j]))

    ans = kruskal(es, n)
    print(ans)

if __name__ == '__main__':
    resolve()

Python: import heapq


def prim(adj):
    INF = 3000
    n = len(adj)
    state, d, p = [False] * n, [INF] * n, [-1] * n
    d[0] = 0
    pq = [(d[0], 0)]
    while pq:
        f, u = heapq.heappop(pq)
        state[u] = True
        if d[u] < f:
            continue
        for v, c in adj[u]:
            if state[v]:
                continue
            if c < d[v]:
                d[v] = c
                p[v] = u
                heapq.heappush(pq, (d[v], v))
    return d


def adj_matrix_to_list(matrix):
    n = len(matrix)
    li = [[] for _ in range(n)]
    for u in range(n):
        for v in range(n):
            if matrix[u][v] != -1:
                li[u].append((v, matrix[u][v]))
    return li


def main():
    n = int(input())
    m = [list(map(int, input().split())) for _ in range(n)]
    adj = adj_matrix_to_list(m)
    print(sum(prim(adj)))


if __name__ == '__main__':
    main()

Python: def main():
     def root(x):
          path=[]
          while x!=P[x]:
               path.append(x)
               x=P[x]
          for i in path:
               P[i]=x
          return x
     
     def is_same_set(x,y):
          return root(x)==root(y)
     
     def unite(x,y):
          P[root(x)]=root(y)
     
     n=int(input())
     P=[i for i in range(n)]
     edge_CostAndVertex=[]
     for i in range(n):
          cost=list(map(int,input().split()))
          for j in range(i):
               if cost[j]!=-1:
                    edge_CostAndVertex.append([cost[j],[i,j]])
                    
     edge_CostAndVertex.sort(key=lambda x:x[0])
     ans=0
     check=[]#連結されている頂点
     main_edge=edge_CostAndVertex[0][1][0]
     for i in edge_CostAndVertex:
          cost_i,a,b=i[0],i[1][0],i[1][1]
          if is_same_set(a,b):
               continue
          else:

               unite(a,b)
               ans+=cost_i
               if a not in check:
                    check.append(a)
               if b not in check:
                    check.append(b)
               if len(check)==n:
                    flag=1
                    for i in range(n):
                         for j in range(i):
                              if is_same_set(i,j):
                                   continue
                              else:
                                   flag=0
                                   break
                    if flag==1:
                         break
                    
     print(ans)
                    
if __name__=='__main__':
     main()

Python: # -*- coding: utf-8 -*-
"""
Created on Sat Jul 14 19:11:44 2018

@author: maezawa
"""

n = int(input())
m = []
for i in range(n):
    mi = list(map(int, input().split()))
    m.append(mi)

#print(*m, sep='\n')

color = [0]*n
d = [10**9]*n
p = [0]*n
p[0] = -1

def prim():
    while True:
        mincost = 10**9
        for i in range(n):
            if color[i] != 2 and d[i] < mincost:
                mincost = d[i]
                u = i
        if mincost == 10**9:
            break

        color[u] = 2

        for v in range(n):
            if color[v] != 2 and m[u][v] != -1:
                if m[u][v] < d[v]:
                    d[v] = m[u][v]
                    p[v] = u
                    color[v] = 1
    sumw = 0
    for i in range(n):
        if p[i] != -1:
            sumw += m[i][p[i]]
    return sumw

print(prim())

Python: def prim(n, M):
    color = [0 for _ in range(n)]
    d = [5000 for _ in range(n)]
    p = [-1 for _ in range(n)]

    d[0] = 0

    while True:
        mincost = 100000
        u = -1

        for i, dt in enumerate(d):
            if dt < mincost and color[i] != 1:
                mincost = dt
                u = i

        # ??´??°???????????£?????´???
        if mincost == 100000:
            break

        color[u] = 1

        for v in range(n):
            # ????????????, ?????????????¨???????????????¨??????
            if M[u][v] != 5000 and color[v] != 1:
                if M[u][v] < d[v]:
                    d[v] = M[u][v]
                    p[v] = u

    all_sum = 0

    for i, p_dt in enumerate(p):
        if p_dt != -1:
            all_sum += M[i][p_dt]

    return all_sum


def main():
    n = int(input())
    M = []

    for _ in range(n):
        dt = input().split(' ')
        M.append([5000 if int(d) == -1 else int(d) for d in dt])

    answer = prim(n, M)

    print(answer)

if __name__ == '__main__':
    main()

Python: n = int(input())
g = [[] for i in range(n)]
for i in range(n):
    *v, = map(int, input().split())
    for j in range(n):
        if v[j] < 0:
            v[j] = 10000
    g[i] = v

ans = 0
t = [0]
v = [i for i in range(1, n)]
while len(t) < n:
    u = [2000, 0, 0]
    for tv in t:
        for vv in v:
            if g[tv][vv] < u[0]:
                u = [g[tv][vv], tv, vv]
    ans += u[0]
    t.append(u[2])
    v.remove(u[2])
print(ans)