Go: package main

import (
	"bufio"
	"fmt"
	"log"
	"math"
	"os"
	"strconv"
	"strings"
)

type color int

const (
	white color = iota // 未訪問
	mst                // MSTとして確定
)

// 頂点
type node struct {
	matrix   []int // 隣接行列
	minToMst int   // MSTへの重み最小値
	parent   int   // 最小値の相手
	color    color
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	n := eGetInt(scanner)

	nodes := make([]node, n)
	for i := 0; i < n; i++ {
		nodes[i].matrix = eAtoi((strings.Fields(eGetline(scanner))))
		nodes[i].parent = -1
		nodes[i].minToMst = math.MaxInt16
		nodes[i].color = white
	}

	// 初回はnode[0]がMSTに入るように,minToMstを設定
	nodes[0].minToMst = 0
	for { // 全部チェックするまで

		// どの頂点を新たにMSTに取り込むか
		min := math.MaxInt16
		u := -1
		for i := 0; i < n; i++ {
			if nodes[i].color == mst {
				continue
			}
			if nodes[i].minToMst < min {
				u = i
				min = nodes[i].minToMst
			}
		}

		if u == -1 {
			break
		}
		// MSTに追加する頂点決定
		nodes[u].color = mst

		// MSTに属していない頂点それぞれについて,MSTとの最小の重みを更新
		for i := 0; i < n; i++ {
			if nodes[i].color == mst {
				continue
			}
			if nodes[i].matrix[u] == -1 {
				// 接してない
				continue
			}
			if nodes[i].matrix[u] < nodes[i].minToMst {
				// node[u]との重みが最小
				nodes[i].minToMst = nodes[i].matrix[u]
				nodes[i].parent = u
			}
		}
	}

	sum := 0
	for _, v := range nodes {
		// node[0]はparentが入っていない
		if v.parent != -1 {
			sum += v.matrix[v.parent]
		}
	}
	fmt.Println(sum)
}

func eGetInt(scanner *bufio.Scanner) int {
	t := eAtoi(strings.Fields(eGetline(scanner)))
	return t[0]
}

func eGetline(p *bufio.Scanner) string {
	if !p.Scan() {
		if err := p.Err(); err != nil {
			log.Fatal(err.Error())
		}
		return ""
	}
	return p.Text()
}

func eAtoi(s []string) []int {
	ints := make([]int, len(s))
	var err error
	for i, e := range s {
		ints[i], err = strconv.Atoi(e)
		if err != nil {
			log.Fatal(err.Error())
		}
	}
	return ints
}

C++: #include <stdio.h>
#include <stdint.h>
#include <iostream>
#include <fstream>
#include <cassert>
#include <climits>

#include <vector>
#include <string>
using namespace std;

#define DEBUG (0)

#if DEBUG
#define DPRINTF(...) do { \
    printf("D(L%d) %s: ", __LINE__, __func__); \
    printf(__VA_ARGS__); \
  } while (false)
#else
#define DPRINTF(...)
#endif // DEBUG


const int kMaxN = 100;
const int kInvalid = INT_MAX;
int g_weightOfVij[kMaxN][kMaxN];
int g_numOfVertices;


struct Edge {
  Edge (int v0, int v1)
    : v0_(v0)
    , v1_(v1)
  { }

  int v0_;
  int v1_;
  int getWeight() { return g_weightOfVij[v0_][v1_]; }
};


struct VisitData {
  VisitData(int num)
    : numOfData_(num)
    , totalWeight_(0)
    {
      memset(visited_, 0, kMaxN);
    }

  bool visited_[kMaxN];
  int numOfData_;
  int totalWeight_;

  bool isAllVisited();

#if DEBUG
  vector<int> path_; // for history of pathes
#endif // DEBUG
};


bool VisitData::isAllVisited()
{
  for (int i = 0; i < numOfData_; i++)
    if (visited_[i] == false)
      return false;

  return true;
}


void printAllWeights()
{
  DPRINTF("Number of vertices %d\n", g_numOfVertices);

  for (int i = 0; i < g_numOfVertices; i++)
  {
    for (int j = 0; j < g_numOfVertices; j++)
    {
      if (j == 0)  DPRINTF("");
      printf(" %d", g_weightOfVij[i][j]);
    }
    cout << endl;
  }
}


void printAllPath()
{
  DPRINTF("Number of vertices %d\n", g_numOfVertices);
  DPRINTF("$src -> $dst ($weight)\n");

  for (int i = 0; i < g_numOfVertices; i++)
  {
    for (int j = 0; j < g_numOfVertices; j++)
    {
      if (g_weightOfVij[i][j] > 0)
        DPRINTF("%d -> %d (%d)\n", i, j, g_weightOfVij[i][j]);
    }
  }
}


void getConnectedVertices(int pos, vector<int> &vertices)
{
  for (int i = 0; i < g_numOfVertices; i++)
    if (g_weightOfVij[pos][i] > 0)
      vertices.push_back(i);

#if 0
  DPRINTF("connected points from %d :", pos);
  for (int i = 0; i < vertices.size(); i++)
    printf(" %d", vertices[i]);

  cout << endl;
#endif
}


/* find unvisited vertices that are connected from the vertices already visited */
void getNextCandidates(const bool visited[kMaxN], vector<Edge> &candidates)
{
#if 0
  DPRINTF("visited:\n");
  for (int i = 0; i < g_numOfVertices; i++)
    DPRINTF("  [%d] = %d\n", i, visited[i]);
#endif

  for (int startV = 0; startV < g_numOfVertices; startV++)
  {
    if (visited[startV] == true)
    {
      // Get all connected vertices
      vector<int> vertices;
      getConnectedVertices(startV, vertices);

      // Remove vertices that are already visited
      for (int nextV : vertices)
      {
        if (visited[nextV] == false)
          candidates.push_back(Edge(startV, nextV));
      }
    }
  }

#if 0
  DPRINTF("Next candidates:\n");
  for (int i = 0; i < candidates.size(); i++)
    printf("  %d -> %d\n", candidates[i].v0_, candidates[i].v1_);
#endif
}


//int findSpanningTree(int vertex, VisitData info /* Not pointer nor reference */)
int findSpanningTree(int vertex, VisitData &info)
{

  assert(info.visited_[vertex] == false);
  info.visited_[vertex] = true;

#if DEBUG
  info.path_.push_back(vertex);
#endif

#if 1 & DEBUG
  DPRINTF("Path:");
  for (int i = 0; i < info.path_.size(); i++)
    printf(" %d", info.path_[i]);
  cout << endl;
#endif

  if (info.isAllVisited())
  {
    DPRINTF("all vertices visited. total weight %d\n", info.totalWeight_);
    return info.totalWeight_;
  }

  vector<Edge> nextPosCandidates;
  getNextCandidates(info.visited_, nextPosCandidates);

  int minWeight = kInvalid;

  for (int i = 0; i < nextPosCandidates.size(); i++)
  {
    const int startV = nextPosCandidates[i].v0_;
    const int nextV = nextPosCandidates[i].v1_;

    VisitData nextInfo = info;
    nextInfo.totalWeight_ += g_weightOfVij[startV][nextV];

    const int weight = findSpanningTree(nextV, nextInfo);

    if (weight != kInvalid && weight < minWeight)
      minWeight = weight;
  }

  DPRINTF("minWeight %d\n", minWeight);
#if 1 & DEBUG
  DPRINTF("  Path:");
  for (int i = 0; i < info.path_.size(); i++)
    printf(" %d", info.path_[i]);
  cout << endl;
#endif

  return minWeight;
}


int main()
{
  cin >> g_numOfVertices; cin.ignore();

  DPRINTF("Number of vertices %d\n", g_numOfVertices);

  for (int i = 0; i < g_numOfVertices; i++)
  {
    for (int j = 0; j < g_numOfVertices; j++)
      cin >> g_weightOfVij[i][j];

    cin.ignore();
  }

#if DEBUG
  DPRINTF("Number of vertices %d\n", g_numOfVertices);
  printAllWeights();
  //printAllPath();
#endif // DEBUG

  const int startPos = 0;
  VisitData info(g_numOfVertices);

  cout << findSpanningTree(startPos, info) << endl;

  return 0;
}

C++: #include<bits/stdc++.h>
using namespace std;
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (a>b) { a=b; return 1; } return 0; }

using Lint=long long;

class UnionFind
{
 public:
    vector<int> par,sz;
    UnionFind(int N):par(N),sz(N){
        for(int i=0;i<N;i++){
            par[i]=i; sz[i]=1;
        }
    }
    int find(int x){
        if(par[x]==x) return x;
        return par[x]=find(par[x]);
    }
    void unite(int x,int y){
        x=find(x); y=find(y);
        if(x==y) return;
        if(sz[x]<sz[y]) swap(x,y);
        par[y]=x;
        sz[x]+=sz[y];
    }
    bool same(int x,int y){ return find(x)==find(y); }
    int size(int x){ return sz[find(x)]; }
    bool root(int x){ return par[x]==x; }
};

struct edge{
    int u,v,cost;
    bool operator<(const edge &e){
        return cost<e.cost;
    }
};

int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);

    int N; cin>>N;
    vector<edge> es;
    for(int i=0;i<N;i++){
        for(int j=0;j<N;j++){
            int c; cin>>c;
            if(i<j and c!=-1) es.push_back({i,j,c});
        }
    }
    sort(es.begin(),es.end());

    int ans=0;
    UnionFind tree(N);
    for(edge e:es){
        if(!tree.same(e.u,e.v)){
            ans+=e.cost;
            tree.unite(e.u,e.v);
        }
    }
    cout<<ans<<endl;
    return 0;
}