Go: package main

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

// Define disjoint-set forests

type vertexNo int

type vertex struct {
	number vertexNo
	rank int
	parent *vertex
}

func makeSet(number vertexNo) vertex {
	return vertex {
		number: number,
		rank: 0,
		parent: nil,
	}
}

func union(x, y *vertex) *vertex {
	return link(findSet(x), findSet(y))
}

func link(x, y *vertex) *vertex {
	if x.rank > y.rank {
		y.parent = x
		return x
	} else {
		x.parent = y
		if x.rank == y.rank {
			y.rank += 1
		}
		return y
	}
}

func findSet(v *vertex) *vertex {
	if v.parent == nil {
		return v
	}
	v.parent = findSet(v.parent)
	return v.parent
}

// Function to calculate minimum spanning tree

type matrix [][]int

type edge struct {
	one vertexNo
	two vertexNo
	weight int
}

const(
	MAX_VERTICES = 100
)

func newEdgesFromMatrix(matrix matrix) []edge {
	edges := make([]edge, 0, MAX_VERTICES * MAX_VERTICES)

	for i := 0; i < len(matrix); i++ {
		row := matrix[i]
		for j := i; j < len(row); j++ {
			if row[j] >= 0 {
				edge := edge{one: vertexNo(i+1), two: vertexNo(j+1), weight: row[j]}
				edges = append(edges, edge)
			}
		}
	}

	return edges
}

func solve(matrix matrix) int {
	nVertices := len(matrix)

	// initialize vertices
	vertices := make([]vertex, nVertices)
	for i := 0; i < nVertices; i++ {
		vertices[i] = makeSet(vertexNo(i+1))
	}

	// prepare edges sorted in the ascending order of weight
	edges := newEdgesFromMatrix(matrix)
	sort.Slice(edges, func(i, j int) bool {
		return edges[i].weight < edges[j].weight
	})

	unionCount := 0
	weightSum := 0
	for unionCount < nVertices-1 {
		for i := 0; i < len(edges); i++ {
			edge := edges[i]
			v1 := &vertices[edge.one-1]
			v2 := &vertices[edge.two-1]
			rep1 := findSet(v1)
			rep2 := findSet(v2)
			if rep1.number == rep2.number {
				continue
			}
			union(rep1, rep2)
			edges = append(edges[0:i], edges[i+1:]...)
			weightSum += edge.weight
			unionCount++
			break
		}
	}

	return weightSum
}

// main

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

	n, err := nextInt(sc)
	if err != nil {
		panic(err)
	}

	matrix := parseMatrix(n, sc)

	edges := newEdgesFromMatrix(matrix)
	sort.Slice(edges, func(i, j int) bool {
		return edges[i].weight < edges[j].weight
	})

	fmt.Println(solve(matrix))
}

func parseMatrix(n int, sc *bufio.Scanner) [][]int {
	matrix := make([][]int, n)
	for i := 0; i < n; i++ {
		matrix[i] = make([]int, n)
		for j := 0; j < n; j++ {
			x, err := nextInt(sc)
			if err != nil {
				panic(err)
			}
			matrix[i][j] = x
		}
	}
	return matrix
}

func nextText(sc *bufio.Scanner) string {
	sc.Scan()
	return sc.Text()
}

func nextInt(sc *bufio.Scanner) (int, error) {
	return strconv.Atoi(nextText(sc))
}

C++: //http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_12_A&lang=jp
#include<vector>
#include<iostream>
#include<queue>
#include<functional>
using namespace std;

constexpr int INF = 1e9;

struct edge
{
	int from, to, cost;
	bool operator>(const edge& other)
	const{
		return cost > other.cost;
	}
};

using edges = vector<edge>;//辺を集めた
using graph = vector<edges>;//i番目のvectorには頂点iから延びる辺全てが並んでる

void add_edge(graph& g, int from, int to, int cost)
{
	g[from].push_back(edge{ from,to,cost });
	g[to].push_back(edge{ to,from,cost });
}

edges prim(const graph& g)
{
	const int N = g.size();//頂点の数
	vector <bool> used(N);
	used[0] = true;
	priority_queue<edge, vector<edge>, greater<edge>>p_que;
	for (auto e : g[0])
	{
		p_que.push(e);
	}
	edges mst;//最小全域木
	while (!p_que.empty())
	{
		auto e=p_que.top();//重みが最小の辺にアクセス
		p_que.pop();//重みが最小の辺をpriority_queueから削除
		if (used[e.to])//重み最小の辺の行き先がすでに訪れたことがある
		{
			continue;
		}
		//重み最小の辺の行き先がすでに訪れたことがない
		mst.push_back(e);//最小全域木に辺を追加
		used[e.to] = true;
		for (auto new_e : g[e.to])//集合Tに新しく含まれた頂点につながっている辺をpriority_queueに追加
		{
			p_que.push(new_e);
		}
	}
	return mst;

}

int main()
{
	int V, E;//Vは頂点　Eは辺の数
	cin >> V >> E;
	graph g(V);//「各頂点とそこから延びる辺」を頂点の数だけ並べた
	for (int i = 0; i < E; i++)
	{
		int from, to, cost;
		cin >> from >> to >> cost;
		add_edge(g, from, to, cost);
	}
	const auto mst = prim(g);
	int ans = 0;
	for (auto& e : mst)
	{
		ans += e.cost;
	}
	cout << ans << endl;
	return 0;
}

C++: #include<bits/stdc++.h>
using namespace std;
vector<vector<int>> A;

int main(){
    int n;cin >> n;
    A.assign(n,vector<int>(n));
    for(auto &i:A)for(auto &j:i) cin >> j;
    vector<int> imat(n);//今行き終わった頂点
    bool flag = true;
    imat[0] = 1;
    int ans = 0;
    while(flag){
        pair<int,int> pa(2001,-1);
        for(int now=0;now<n;now++){
            if(!imat[now]) continue;
            for(int to=0;to<n;to++){
                if(imat[to]) continue;
                if(A[now][to]==-1) continue;
                if(pa.first>A[now][to]){
                    pa.first = A[now][to];
                    pa.second = to;
                }
            }
        }
        imat[pa.second] = 1;
        ans+=pa.first;
        bool e = true;
        for(int i=0;i<n;i++){
            if(imat[i]==0){
                e = false;
                break;
            }
        }
        if(e) flag = false;
    }
    cout << ans << endl;
}

C++: #include<iostream>
#include<climits>
using namespace std;
typedef struct{
  int a[2000];
  bool f;
}node;

node T[103];
int m;
int n;
int ans;
int cnt;
int num;
void route(){
  m=INT_MAX;
  if(cnt==n)return;
  for(int i=0;i<n;i++){
    if(T[i].f==true){
      for(int j=0;j<n;j++){
	if(m>T[i].a[j]){
	  m=T[i].a[j];
	  num=j;
	}
      }
    }
  }
  ans+=m;
  cnt++;
  T[num].f=true;
  route();
}
int main(){
  int key;
  cin>>n;
  for(int i=0;i<n;i++){
    for(int j=0;j<n;j++){
      cin>>key;
      if(key==-1)T[i].a[j]=INT_MAX;
      else T[i].a[j]=key;
    }
  }
  T[0].f=true;
  route();
  cout<<ans<<endl;
  return 0;
}

C++: #include<bits/stdc++.h>

#define int long long int
#define rep(a,b,c) for(int a=b;a<c;a++)
#define repm(a,b,c) for(int a=(b-1);a>=c;a--)
#define pb push_back
#define str string
#define sf(a) scanfs("%d",&a)
#define pb push_back
#define mp make_pair
#define Fi first
#define Se second
#define ALL(v) (v).begin(), (v).end()
using namespace std;
const int INF = 1e18 + 9;
const int Mod = 1e9 + 7;
inline int replac(str s){double ans=0;rep(i,0,s.length()){ans+=(s[i]-'0')*pow(10,s.length()-i-1);}return (int)ans;}
inline string numstr(int m){str s="";while(m>0){char c;int a=m/10;if(a>0)a=m%(a*10);else a=m;c=(char)('0'+a);s+=c;m/=10;}str st="";for(int i=s.size()-1;i>=0;i--){st+=s[i];}return st;}
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef vector<pii> vii;
int cost[1001][1001];///i->j=cost;
int mincost[1001];///shougoX->minimum-cost
bool used[1001];///inX?
int N;///ten-kazu
int prim(){
    rep(i,0,N){
        mincost[i]=INF;
        used[i]=false;
    }
    mincost[0] = 0;
    int res = 0;

    while(true){
        int v = -1;
        rep(u,0,N){
            if(!used[u]&&(v == -1 || mincost[u] < mincost[v]))v=u;
        }
        if(v == -1)break;
        used[v] = true;
        res += mincost[v];

        rep(i,0,N){
            mincost[i] = min(mincost[i], cost[v][i]);
        }
    }
    return res;
}

signed main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    map<int,int> mx,my;
    int n;
    cin >> n;
    N=n;
    rep(i,0,1001){
        rep(j,0,1001){
            cost[i][j]=INF;
        }
    }
    rep(i,0,n){
        rep(j,0,n){
            int x;cin >> x;
            if(x==-1)continue;
            cost[i][j]=x;
            cost[j][i]=x;
        }
    }
    cout << prim() << endl;
    return 0;
}