Go: package main

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

var scanner = bufio.NewScanner(os.Stdin)

func nextString() string {
	scanner.Scan()
	return scanner.Text()
}

func nextInt() int {
	n, err := strconv.Atoi(nextString())
	if err != nil {
		fmt.Printf("strconv.Atoi failed: %v\n", err)
	}
	return n
}

type ElementKey int
type Node struct {
	key    ElementKey
	parent *Node
	rank   int
}

func newNode(key ElementKey) *Node {
	node := Node{}
	node.key = key
	node.parent = &node
	node.rank = 0

	return &node
}

func union(x, y *Node) {
	xSet := findSet(x)
	ySet := findSet(y)
	link(xSet, ySet)
}

func link(x, y *Node) {
	if x.rank > y.rank {
		y.parent = x
	} else {
		x.parent = y

		if x.rank == y.rank {
			y.rank++
		}
	}
}

func findSet(x *Node) *Node {
	if x != x.parent {
		x.parent = findSet(x.parent)
	}
	return x.parent
}

func newDisjointSets(nSets int) *DisjointSets {
	sets := DisjointSets{}
	sets.keyToNode = map[ElementKey]*Node{}
	for i := 0; i < nSets; i++ {
		key := ElementKey(i)
		sets.keyToNode[key] = newNode(key)
	}
	return &sets
}

type DisjointSets struct {
	keyToNode map[ElementKey]*Node
}

func (sets *DisjointSets) union(x, y ElementKey) {
	xNode := sets.keyToNode[x]
	yNode := sets.keyToNode[y]
	union(xNode, yNode)
}

func (sets DisjointSets) findSet(x ElementKey) *Node {
	xNode := sets.keyToNode[x]
	return findSet(xNode)
}

type Edge struct {
	i, j   int
	weight int
}

func main() {
	scanner.Split(bufio.ScanWords)

	n := nextInt()
	sets := newDisjointSets(n)
	edges := []Edge{}
	a := make([][]int, n)
	for i := 0; i < n; i++ {
		a[i] = make([]int, n)
		for j := 0; j < n; j++ {
			a[i][j] = nextInt()
			if a[i][j] >= 0 {
				e := Edge{
					i:      i,
					j:      j,
					weight: a[i][j],
				}
				edges = append(edges, e)
			}
		}
	}
	sort.Slice(edges, func(i, j int) bool { return edges[i].weight < edges[j].weight })
	totalWeight := 0
	for _, edge := range edges {
		i := ElementKey(edge.i)
		j := ElementKey(edge.j)
		if sets.findSet(i) != sets.findSet(j) {
			totalWeight += edge.weight
			sets.union(i, j)
		}
	}
	fmt.Println(totalWeight)
}

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

using namespace std;
using LL = long long;
using P = pair<int, int>;
using Tapris = tuple<int, int, int>;

#define REP(i, n) for(LL i = 0; i < n; ++i)
#define FOR(i, a, n) for(LL i = a; i < n; ++i)
#define pb(a) push_back(a)
#define all(x) (x).begin(),(x).end()

const int INF = (int)1e9;
const LL INFL = (LL)1e15;
const int MOD = 1e9 + 7;

int dy[]={0, 0, 1, -1, 0};
int dx[]={1, -1, 0, 0, 0};

//#define int long long
// 0-indexedに注意
template<typename T>
struct Edge {
    int to;
    T cost;
    Edge(int to, T cost) : to(to), cost(cost) {}
};

template<typename T>
class Prim{
    private:
        vector<vector<Edge<T>>> graph;
        vector<bool> used;
    public:
        Prim(int n);
        void AddEdge(int from, int to, T cost);
        T Run();
};

template<typename T>
Prim<T>::Prim(int n): graph(n), used(n, false) {}

template<typename T>
void Prim<T>::AddEdge(int from, int to, T cost){
    graph[from].push_back(Edge<T>(to, cost));
}

template<typename T>
T Prim<T>::Run(){
    using Pi = pair<T, int>;
    T total = 0;
    priority_queue<Pi, vector<Pi>, greater<Pi>> que;
    que.emplace(0, 0);
    while(!que.empty()){
        Pi p = que.top();
        que.pop();
        if(used[p.second]) continue;
        used[p.second] = true;
        total += p.first;
        for(auto &e : graph[p.second]){
            que.emplace(e.cost, e.to);
        }
    }
    return total;
}
/*************** using variables ***************/

/**********************************************/

signed main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    
    int n;
    cin >> n;
    Prim<int> prim(n);
    REP(i, n){
        REP(j, n){
            int x;
            cin >> x;
            if(x != -1) prim.AddEdge(i, j, x);
        }
    }

    cout << prim.Run() << endl;
}

C++: #include <iostream> // cout, endl, cin
#include <string> // string, to_string, stoi
#include <vector> // vector
#include <algorithm> // min, max, swap, sort, reverse, lower_bound, upper_bound
#include <utility> // pair, make_pair
#include <tuple> // tuple, make_tuple
#include <map> // map
#include <queue> // queue, priority_queue
#include <set> // set
#include <stack> // stack
#include <deque> // deque
#define ll long long
#define ALL(x) (x).begin(),(x).end()
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define vi vector<int>
#define vvi vector<vector<int>>
using namespace std;

class UnionFind {
private:
    vector<vector<int>> Graph; // {ID,Number,ParentID,Height}

    void flatten(int x, int rootid) {
        int parentid = Graph[x][0];
        while (Graph[parentid][0] != Graph[parentid][2]) {
            Graph[parentid][2] = rootid;
            int next = Graph[parentid][2];
            parentid = next;
        }
    }
public:
    void push(int x) {
        int i = Graph.size();
        Graph.push_back({ i,x,i,1 });
    }
    void unite(int x, int y) {
        int hx = Graph[root(x)][3];
        int hy = Graph[root(y)][3];
        if (hx < hy) {
            Graph[root(x)][2] = root(y);
            flatten(x, root(y));
        }
        else if(hx == hy){
            Graph[root(y)][2] = root(x);
            Graph[root(x)][3]++;
            flatten(y, root(x));
        }
        else {
            Graph[root(y)][2] = root(x);
            flatten(y, root(x));
        }
    }
    bool same(int x, int y) {
        return root(x) == root(y);
    }

   
    int root(int x) {
        int parentid = Graph[x][0];
        while (Graph[parentid][0] != Graph[parentid][2]) {
            int next = Graph[parentid][2];
            parentid = next;
        }
       
        return parentid;
    }
};

int main() {
    int n; cin >> n;
    vector<vector<int>> edges; // {weight, from_id, to_id} both 0-indexed
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            int w; cin >> w;
            if (w == -1) {
                continue;
            }
            else {
                vector<int> temp_edge = { w,i,j };
                edges.push_back(temp_edge);
            }
        }
    }

    sort(ALL(edges));
    int n_edges = 0;
    int TotalCost = 0;

    UnionFind uf;
    for (int i = 0; i < n; i++) uf.push(i);

    for (int i = 0; n_edges < n - 1; i++) {
        vector<int> edge = edges[i];
       
        if (uf.root(edge[1]) != uf.root(edge[2])) {
            uf.unite(edge[1], edge[2]);
            n_edges++;
            TotalCost += edge[0];
        }
    }


    cout << TotalCost << endl;
}

C++: #include<iostream>
using namespace std;
static const int MAX = 100;
static const int INFTY = (1<<21);
static const int WHITE = 0;
static const int GRAY = 1;
static const int BLACK = 2;

int n, N[MAX][MAX];

int prim()
{
  int u,minv;
  int d[MAX],p[MAX],color[MAX];
  int i=0;
  int v=0;
  int j=0;

  for (i=0;i<n;i++)
    {
      d[i] = INFTY;
      p[i] = -1;
      color[i] = WHITE;
    }

  d[0] = 0;

  while(1)
    {
      minv = INFTY;
      u = -1;
      for( i=0 ; i<n ;i ++)
	{
	  if(minv>d[i] && color[i]!=BLACK)
	    {
	      u=i;
	      minv=d[i];
	    }
	}
      if( u==-1 )break;
      color[u] = BLACK;
      for( v=0 ; v<n ; v++ )
	{
	  if(color[v]!=BLACK && N[u][v]!=INFTY)
	    {
	      if(d[v]>N[u][v])
		{
		  d[v] = N[u][v];
		  p[v] = u;
		  color[v] = GRAY;
		}
	    }
	}
    }
  int sum=0;
  for(i=0;i<n;i++)
    {
      if(p[i]!=-1)
	{
	  sum += N[i][p[i]];
	}
    }

      return sum;
    }

  int main()
  {
    int i=0;
    int j=0;
    cin>>n;

    for(i=0;i<n;i++)
      {
	for( j=0 ; j<n ; j++ )
	  {
	    int e;
	    cin>>e;
	    N[i][j] = (e == -1)? INFTY : e;
	  }
      }

    cout<<prim()<<endl;

    return 0;
  }