Go: package main

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

const BIG_COST = 3000

const (
	ST_NOT_YET = iota
	ST_JOINED
)

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)

	nNodes := scanInt(sc)
	costs := make([][]int, nNodes)

	for r := 0; r < nNodes; r++ {
		costs[r] = make([]int, nNodes)
		for c := 0; c < nNodes; c++ {
			costs[r][c] = scanInt(sc)
		}
	}

	states := make([]int, nNodes)
	minCosts := make([]int, nNodes)

	for i := 1; i < nNodes; i++ {
		minCosts[i] = BIG_COST
	}

	for {
		var u int
		minCost := BIG_COST

		for i := 0; i < nNodes; i++ {
			if states[i] != ST_JOINED && minCosts[i] < minCost {
				minCost = minCosts[i]
				u = i
			}
		}

		// 全てのノードが MST に JOIN できたので終了。
		if minCost == BIG_COST {
			break
		}

		states[u] = ST_JOINED

		for v := 0; v < nNodes; v++ {
			cost := costs[u][v]

			// MST内の u と MST外の v との辺の重みをそれぞれ minCosts[v] として
			// 保存しておく。このうち辺の重みが最小となる v が次のループで MST に JOIN する。
			if states[v] != ST_JOINED && cost != -1 && cost < minCosts[v] {
				minCosts[v] = cost
			}
		}
	}

	sum := 0
	for _, cost := range minCosts {
		sum += cost
	}
	fmt.Println(sum)
}

func scanInt(sc *bufio.Scanner) int {
	sc.Scan()
	v, _ := strconv.Atoi(sc.Text())
	return v
}

Python: a=input()
matrix=[]
for i in range(int(a)):
	matrix.append(list(map(int,input().split())))

# ?????????O(n)????????£?????????
class union_find(object):
 	"""union-find tree"""
 	def __init__(self, length):
 		self.length = length
 		self.unionnumber=0
 		self.unionlist=[[]]
 		self.num=list(-1 for i in range(length))

 	def unite(self,i,j):
 		if self.num[i]==-1:
 			if self.num[j]==-1:
 				self.unionlist[self.unionnumber].extend([i,j])
 				self.num[i]=self.unionnumber
 				self.num[j]=self.unionnumber
 				self.unionnumber+=1
 				self.unionlist.append([])
 			else:
 				tmp=i 
 				i=j 
 				j=tmp 
 		if self.num[i]!=-1:
 			if self.num[j]!=-1:
 				if self.num[i]==self.num[j]:
 					pass
 				else:
 					self.unionlist[self.num[i]].extend(self.unionlist[self.num[j]])
 					tmp=self.num[j]
 					for k in self.unionlist[self.num[j]]:
 						self.num[k]=self.num[i]
 					self.unionlist[tmp]="del"
 			else:
 				self.num[j]=self.num[i]
 				self.unionlist[self.num[i]].append(j)

 	def same(self,i,j):
 		if self.num[i]==-1 or self.num[j]==-1:
 			return(False)
 		else:
 			return(self.num[i]==self.num[j])

# ?????????=-1
def Kruskal(matrix):
	length=len(matrix)
	edgelist=[]
	for i in range(length):
		for j in range(i+1):
			if matrix[i][j]!=-1:
				edgelist.append([j,i,matrix[i][j]])
	edgelist.sort(key=lambda x:x[2],reverse=True)
	result=[[-1 for i in range(length)] for j in range(length)]
	union=union_find(length)
	while(edgelist!=[]):
		edge=edgelist.pop()
		i,j,score=edge
		if union.same(i,j):
			pass
		else:
			union.unite(i,j)
			result[i][j]=score
			result[j][i]=score
		
	return(result)

a=Kruskal(matrix)
count=0
for i in range(len(a)):
	for j in range(i):
		if a[i][j]!=-1:
			count+=a[i][j]

print(count)

Python: INF = 1e9

n = int(input())
adj_matrix = [list(map(int, input().split())) for i in range(n)]


def prim(x):
    isVisited = [False] * x
    d = [INF] * x 
    d[0] = 0
    p = [-1] * x 
    
    while True:
        min_cost = INF
        
        for i in range(x):
            if isVisited[i] != True and d[i] < min_cost:
                min_cost = d[i]
                u = i
        
        if min_cost == INF:
            break
        
        isVisited[u] = True
        
        for v in range(x):
            if isVisited[v] != True and adj_matrix[u][v] != -1:
                if adj_matrix[u][v] < d[v]:
                    d[v] = adj_matrix[u][v]
                    p[v] = u
    return sum(d)

print(prim(n))

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

for _ in range(n):
    tmp = [int(x) for x in input().split()]
    m.append(tmp)

#辺を全て持つリストを作る
edge_list = [] 
j = 1
for i in range(n-1):
    for k,x in enumerate(m[i][j:]):
        if x != -1:
            edge_list.append((x,i,k+j))
        else:
            pass
    j += 1
edge_list.sort()

root_list = [i for i in range(n)]

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

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

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

cost = 0
for x in edge_list:
    w,p,q = x
    if is_same_root(p,q):
        continue
    else:
        cost += w
        unite(p,q)

print(cost)

Python: inf = float("inf")
class Node():

    def __init__(self, _id):
        self.id = _id
        self.d = inf
        self.pi = None
        self.color = 0
    
    def input_data(self):
        data = [int(i) for i in input().split()]
        self.adj = {G[i]: d
                    for i, d in enumerate(data)
                    if d != -1}
    
    def __hash__(self):
        return hash(self.id)
        
    

def prim():
    G[0].d = 0
    while True:
        mincost = inf
        for i in G:
            if i.color != 1 and i.d < mincost:
                mincost = i.d
                u = i
        
        if mincost == inf:
            break

        u.color = 1
        for v in u.adj.keys():
            if v.color != 1 and u.adj[v] < v.d:
                v.pi = u.id
                v.d = u.adj[v]

if __name__ == "__main__":
    n = int(input())
    G = [Node(i) for i in range(n)]
    [i.input_data() for i in G]
    prim()
    print(sum(g.d for g in G))

Python: n = int(input())
inf = float('inf')
graphs = []

for i in range(n):
    weights = list(map(int, input().split()))
    weights = [inf if weight == -1 else weight for weight in weights]
    graphs.append(weights)
# print(graphs)
# M =graphs
color = ['WHITE' for _ in range(n)]
d = [inf for _ in range(n)]
p = [i for i in range(n)]


def prim():
    d[0] = 0
    p[0] = -1
    while True:
        min_cost = inf
        for i in range(n):
            if color[i] != 'BLACK' and d[i] < min_cost:
                min_cost = d[i]
                u = i
        if min_cost == inf:
            break
        color[u] = 'BLACK'

        for v in range(n):
            if color[v] != 'BLACK' and graphs[u][v] != inf:
                if graphs[u][v] < d[v]:
                    d[v] = graphs[u][v]
                    p[v] = u
                    color[v] = 'GRAY'


prim()
# print(d)
# print(p)
print(sum(d))

Python: def main():
    N = int(input())
    c = [[int(i) for i in input().split()] for j in range(N)]
    edges = []
    for i in range(N):
        for j in range(i+1, N):
            if c[i][j] != -1:
                edges.append((c[i][j], (i, j)))
    edges.sort()

    par = [i for i in range(N)]
    rank = [0 for i in range(N)]

    def find_root(x):
        if par[x] == x:
            return x
        else:
            par[x] = find_root(par[x])
            return par[x]

    def is_same_group(x, y):
        return find_root(x) == find_root(y)

    def unite(x, y):
        x = find_root(x)
        y = find_root(y)
        if x == y:
            return
        if rank[x] < rank[y]:
            par[x] = y
        else:
            par[y] = x
            if rank[x] == rank[y]:
                rank[x] += 1

    ans = 0
    for c, e in edges:
        if find_root(e[0]) != find_root(e[1]):
            unite(e[0], e[1])
            ans += c
    print(ans)


if __name__ == '__main__':
    main()