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 C# (judge verdict: Accepted)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CompProgLib;

namespace ALDS1_12_A
{
    public class Program

    {
        public static void Main(string[] args)
        {
            Graph gr = new Graph();
            int n = ReadInt();

            for (int i = 0 ; i < n ; i++)
            {
                gr.SetGraph(i);
                int[] line = ReadIntAr();
                for (int j = 0 ; j < n ; j++)
                {
                    if (line[j] != -1) gr.SetGraph(i,j, line[j]);
                }
            }

            int res = gr.Prim();
            Console.WriteLine(res);
        }

        static string ReadSt() { return Console.ReadLine(); }
        static int ReadInt() { return int.Parse(Console.ReadLine()); }
        static long ReadLong() { return long.Parse(Console.ReadLine()); }
        static double ReadDouble() { return double.Parse(Console.ReadLine()); }
        static string[] ReadStAr(char sep = ' ') { return Console.ReadLine().Split(sep); }
        static int[] ReadIntAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => int.Parse(e)); }
        static long[] ReadLongAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => long.Parse(e)); }
        static double[] ReadDoubleAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => double.Parse(e)); }

    }

}

namespace CompProgLib
{
    public class Graph
    {
        public class Node
        {
            public List<KeyValuePair<int, int>> Vertex { get; internal set; }
            public int D { get; internal set; }
            public int F { get; internal set; }
            public bool IsVisited { get; internal set; }
            public int Group { get; internal set; }
            public int Depth { get; internal set; }

            public Node(List<int> v)
            {
                Vertex = v.Select(x => new KeyValuePair<int, int>(x, -1)).ToList();
                Depth = -1;
                Group = -1;
            }

            public Node(List<KeyValuePair<int, int>> v)
            {
                Vertex = v;
                Depth = -1;
                Group = -1;
            }

        }

        public Dictionary<int, Node> Adj { get; set; }

        public Graph()
        {
            Adj = new Dictionary<int, Node>();
        }

        public void AddVertex(int index, int v)
        {
            if (!Adj[index].Vertex.Contains(new KeyValuePair<int, int>(v, -1)))
            {
                Adj[index].Vertex.Add(new KeyValuePair<int, int>(v, -1));
            }
        }


        /// <summary>
        /// 指定した頂点をセットする
        /// </summary>
        /// <param name="index">頂点u</param>
        /// <param name="item">頂点uに接続する頂点</param>
        public void SetGraph(int index, int[] item)
        {
            if (item == null)
            {
                Adj.Add(index, new Node(new List<int>()));
            }
            else
            {
                Adj.Add(index, new Node(item.ToList()));
            }
        }

        public void SetGraph(int index, List<KeyValuePair<int, int>> item)
        {
            if (item == null)
            {
                Adj.Add(index, new Node(new List<int>()));
            }
            else
            {
                Adj.Add(index, new Node(item));
            }
        }

        public void SetGraph(int index, int v, int c)
        {
            if (!Adj.ContainsKey(index))
            {
                SetGraph(index);
            }
            Adj[index].Vertex.Add(new KeyValuePair<int, int>(v, c));
        }

        public void SetGraph(int index)
        {
            if (!Adj.ContainsKey(index))
            {
                Adj.Add(index, new Node(new List<KeyValuePair<int, int>>()));
            }
        }


        /// <summary>
        /// 行列を0で初期化する
        /// </summary>
        public void Clear() { Adj.Clear(); }

        /// <summary>
        /// 深さ優先探索
        /// </summary>
        private int Time = 0;
        public void DFS(int v)
        {
            Adj[v].D = ++Time;
            Adj[v].IsVisited = true;
            foreach (KeyValuePair<int, int> vertex in Adj[v].Vertex)
            {
                if (!Adj[vertex.Key].IsVisited) DFS(vertex.Key);
            }
            Adj[v].F = ++Time;
        }

        /// <summary>
        /// 訪問済フラグをクリアする
        /// </summary>
        private void InitVisitFlag()
        {
            foreach (KeyValuePair<int, Node> item in Adj) item.Value.IsVisited = false;
        }

        /// <summary>
        /// 幅優先探索
        /// </summary>
        /// <param name="v"></param>
        public void BFS(int v)
        {
            Queue<Node> que = new Queue<Node>();

            Adj[v].Depth = 0;
            Adj[v].IsVisited = true;
            que.Enqueue(Adj[v]);

            while (que.Count() != 0)
            {
                Node node = que.Dequeue();
                foreach (KeyValuePair<int, int> vertex in node.Vertex)
                {
                    if (!Adj[vertex.Key].IsVisited)
                    {
                        Adj[vertex.Key].IsVisited = true;
                        Adj[vertex.Key].Depth = node.Depth + 1;
                        que.Enqueue(Adj[vertex.Key]);

                    }
                }
            }

        }

        /// <summary>
        /// 頂点間の最短距離を返す
        /// </summary>
        /// <param name="start">始点</param>
        /// <param name="end">終点</param>
        /// <returns>
        /// 始点と終点の距離
        /// 始点と終点が連結されていない場合は-1を返す
        /// </returns>
        public int GetDistance(int start, int end)
        {
            InitVisitFlag();
            Queue<Node> que = new Queue<Node>();

            Adj[start].IsVisited = true;
            Adj[start].Depth = 0;

            if (start == end) return Adj[start].Depth;
            que.Enqueue(Adj[start]);

            while (que.Count() != 0)
            {
                Node node = que.Dequeue();
                foreach (KeyValuePair<int, int> vertex in node.Vertex)
                {
                    if (!Adj[vertex.Key].IsVisited)
                    {
                        Adj[vertex.Key].IsVisited = true;
                        Adj[vertex.Key].Depth = node.Depth + 1;

                        if (vertex.Key == end) return Adj[vertex.Key].Depth;
                        que.Enqueue(Adj[vertex.Key]);
                    }
                }
            }
            return -1;
        }

        /// <summary>
        /// 連結である頂点に同一のグループ番号をセットする
        /// </summary>
        public void SetGroup()
        {
            int group = 0;
            foreach (KeyValuePair<int, Node> item in Adj)
            {
                if (item.Value.Group < 0)
                {
                    _SetGroup(item.Key, group);
                }
                group++;
            }
        }

        private void _SetGroup(int key, int group)
        {

            Queue<Node> que = new Queue<Node>();

            Adj[key].Group = group;
            que.Enqueue(Adj[key]);

            while (que.Count() != 0)
            {
                Node node = que.Dequeue();
                foreach (KeyValuePair<int, int> vertex in node.Vertex)
                {
                    if (Adj[vertex.Key].Group < 0)
                    {
                        Adj[vertex.Key].Group = group;
                        que.Enqueue(Adj[vertex.Key]);
                    }
                }
            }
        }

        /// <summary>
        /// 最小全域木のコストを求める
        /// </summary>
        /// <returns></returns>
        class Edge : IComparable<Edge>
        {
            public int NextV { get; set; }
            public int Cost { get; set; }

            public Edge(int nextV,int cost)
            {
                NextV = nextV;
                Cost = cost;
            }

            public int CompareTo(Edge other)
            {
                return -1 * Cost.CompareTo(other.Cost);
            }
        }
        public int Prim()
        {
            PriorityQueue<Edge> pq = new PriorityQueue<Edge>();
            int totalCost = 0;
            pq.Enqueue(new Edge(Adj.First().Key, 0));

            while (pq.Count >0)
            {
                Edge e = pq.Dequeue();
                if (!Adj[e.NextV].IsVisited)
                {
                    Adj[e.NextV].IsVisited = true;
                    totalCost += e.Cost;
                    foreach (KeyValuePair<int, int> vertex in Adj[e.NextV].Vertex)
                    {
                        pq.Enqueue(new Edge(vertex.Key, vertex.Value));
                    }
                }

            }

            return totalCost;

        }
    }
}

namespace CompProgLib
{
    public class PriorityQueue<T> where T : IComparable<T>

    {

        private List<T> Buffer { get; set; }

        public int Count { get { return Buffer.Count; } }

        public PriorityQueue() { Buffer = new List<T>(); }
        public PriorityQueue(int capacity) { Buffer = new List<T>(capacity); }


        /// <summary>
        /// ヒープ化されている配列リストに新しい要素を追加する。
        /// </summary>
        public void Enqueue(T item)
        {
            int n = Buffer.Count;
            Buffer.Add(item);

            while (n != 0)
            {
                int i = (n - 1) / 2;
                if (Buffer[n].CompareTo(Buffer[i]) > 0)
                {
                    T tmp = Buffer[n]; Buffer[n] = Buffer[i]; Buffer[i] = tmp;
                }
                n = i;
            }
        }

        /// <summary>
        /// ヒープから最大値を取り出し、削除する。
        /// </summary>
        public T Dequeue()
        {
            T ret = Buffer[0];
            int n = Buffer.Count - 1;
            Buffer[0] = Buffer[n];
            Buffer.RemoveAt(n);

            for (int i = 0, j ; (j = 2 * i + 1) < n ;)
            {
                if ((j != n - 1) && (Buffer[j].CompareTo(Buffer[j + 1]) < 0))
                    j++;
                if (Buffer[i].CompareTo(Buffer[j]) < 0)
                {
                    T tmp = Buffer[j]; Buffer[j] = Buffer[i]; Buffer[i] = tmp;
                }
                i = j;
            }
            return ret;
        }

        /// <summary>
        /// ヒープから最大値を参照する。
        /// </summary>
        public T Peek()
        {
            if (Count == 0) throw new InvalidOperationException();
            return this.Buffer[0];
        }
    }
}