Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Minimum Spanning Tree

For a given weighted graph $G = (V, E)$, find the minimum spanning tree (MST) of $G$ and print total weight of edges belong to the MST.

Input

In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, a $n \times n$ adjacency matrix $A$ which represents $G$ is given.
$a_{ij}$ denotes the weight of edge connecting vertex $i$ and vertex $j$. If there is no edge between $i$ and $j$, $a_{ij}$ is given by -1.

Output

Print the total weight of the minimum spanning tree of $G$.

Constraints

$1 \leq n \leq 100$

$0 \leq a_{ij} \leq 2,000$ (if $a_{ij} \neq -1$)

$a_{ij} = a_{ji}$

$G$ is a connected graph

Sample Input 1

5
-1 2 3 1 -1
2 -1 -1 4 -1
3 -1 -1 1 1
1 4 1 -1 3
-1 -1 1 3 -1

Sample Output 1

5

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

Solution in JAVA (judge verdict: Accepted)

import java.util.Scanner;

public class Main {

    static Scanner sc = new Scanner(System.in);
    static int V;
    static int[][] G = new int[105][105];
    static final int INF = 1 << 31 - 1;

    public static void main(String[] args) {
        V = sc.nextInt();

        int v;
        for (int i = 0; i < V; i++) {
            for (int j = 0; j < V; j++) {
                v = sc.nextInt();
                G[i][j] = v != -1 ? v : INF;
            }
        }

        int ans = solvePrim();
        System.out.println(ans);
    }

    /*
    This function find the Minimum Spanning Tree (MST) in O(V^2).

      V: Number of vertexes.
      G: Costs between two vertexes (values of edges). If the edge does not exists, INF should be set.

    Return the total cost of the MST, T.
    */
    public static int solvePrim() {

        int[] cost = new int[V];  // the cost for adding vertex v in G - T to T
        boolean[] used = new boolean[V];  // whether the vertex v exists in T

        for (int i = 0; i < V; i++) {
            cost[i] = INF;
            used[i] = false;
        }

        cost[0] = 0;
        int ret = 0;

        while (true) {
            int v = -1;
            for (int u = 0; u < V; u++) {
                if (used[u]) {
                    continue;
                }
                if (v == -1 && cost[u] != INF) {
                    v = u;
                    continue;
                }
                if (cost[u] < cost[v]) {
                    v = u;
                }
            }

            if (v == -1) break;

            used[v] = true;
            ret += cost[v];

            for (int u = 0; u < V; u++) {
                cost[u] = Math.min(cost[u], G[u][v]);
            }
        }

        return ret;
    }
}