Go: package main

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

const (
	white int = iota
	gray
	black
)
const INFTY int = 2001

var G [][]int
var color []int
var d []int
var p []int
var N int

func prim() int {
	u := 0
	d[u] = 0
	for {
		minCost := INFTY
		for i:=0; i<N; i++ {
			if color[i] != black && d[i] < minCost {
				minCost = d[i]
				u = i
			}
		}

		if minCost == INFTY {
			break
		}

		color[u] = black

		for v:=0; v<N; v++ {
			if color[v] != black && G[u][v] != -1 {
				if G[u][v] < d[v] {
					d[v] = G[u][v]
					p[v] = u
					color[v] = gray
				}
			}
		}
	}
	// sum
	sum := 0
	for i:=0; i<N; i++ {
		if p[i] != -1 {
			sum += G[i][p[i]]
		}
	}
	return sum
}




func initVariable(N int) {
	G = make([][]int, N)
	for i:=0; i<N; i++ {
		G[i] = make([]int, N)
	}
	color = make([]int, N)
	d = make([]int, N)
	p = make([]int, N)
	for i:=0; i<N; i++ {
		d[i] = INFTY
		p[i] = -1
	}
}

func nextInt(scanner *bufio.Scanner) int {
	scanner.Scan()
	num, _ := strconv.Atoi(scanner.Text())
	return num
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	N = nextInt(scanner)
	initVariable(N)
	for i:=0; i<N; i++ {
		for j:=0; j<N; j++ {
			G[i][j] = nextInt(scanner)
		}
	}
	fmt.Printf("%d\n", prim())
}

C++: #include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

const long INF=1000000000;

int main(){
	int n;
	long a[100][100];
	
	scanf(" %d", &n);
	for(int i=0; i<n; ++i){
		for(int j=0; j<n; ++j){
			long p;
			scanf(" %ld", &p);
			if(p==-1) a[i][j]=INF;
			else a[i][j]=p;
		}
	}
	
	//prim
	
	int visit[100]={0}; //????¨??????§?????????
	
	int p[100]; //MST???????????????
	p[0]=-1;
	
	int d[100];
	for(int i=0; i<n; ++i) d[i]=INF;
	d[0]=0; //????????????0???????????????????????????
	
	int u;
	while(1){
		long mincost=INF;
		
		for(int i=0; i<n; ++i){
			if(visit[i]!=-1 && d[i]<mincost){
				mincost=d[i];
				u=i;	
			}
		}
		
		if(mincost==INF) break; //????????\?????????????????????
		
		visit[u]=-1; //?¨??????????
		
		for(int i=0; i<n; ++i){
			if(visit[i]!=-1 && a[u][i]<d[i]){
				d[i]=a[u][i];
				p[i]=u;
				visit[i]=1; //?¬??¨???????????\´???????£?
			}
		}
		
	}
	
	long ans=0;
	for(int i=0; i<n; ++i){
		if(p[i]!=-1) ans+=a[i][p[i]];
		
	}
	printf("%ld\n", ans);
}