AOJ本の読書メモ   AOJ    次のAOJの問題へ    前のAOJの問題へ

ALDS1_12_A: Minimum Spanning Tree


問題へのリンク


C#のソース

using System;
using System.Collections.Generic;
using System.Linq;

// Q040 最小全域木 https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_12_A&lang=ja
class Program
{
    static string InputPattern = "InputX";

    static List<string> GetInputList()
    {
        var WillReturn = new List<string>();

        if (InputPattern == "Input1") {
            WillReturn.Add("5");
            WillReturn.Add(" -1 2 3 1 -1");
            WillReturn.Add(" 2 -1 -1 4 -1");
            WillReturn.Add(" 3 -1 -1 1 1");
            WillReturn.Add(" 1 4 1 -1 3");
            WillReturn.Add(" -1 -1 1 3 -1");
            //5
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static void Main()
    {
        List<string> InputList = GetInputList();

        int[] wkArr = { };
        Action<string> SplitAct = pStr =>
            wkArr = pStr.Split(' ').Select(X => int.Parse(X)).ToArray();

        int N = int.Parse(InputList[0]);

        int UB = N - 1;
        int[,] MatrixArr = new int[UB + 1, UB + 1];

        for (int Y = 0; Y <= UB; Y++) {
            SplitAct(InputList[Y + 1].TrimStart());
            for (int X = 0; X <= UB; X++) {
                MatrixArr[X, Y] = wkArr[X];
            }
        }
        // PrintBan(MatrixArr);

        var InsPQueue = new PQueue();
        PQueue.PQueueJyoutaiDef WillEnque;

        // 指定した頂点からの辺をプライオリティーキューに入れる
        Action<int> EnqueueAct = pNode =>
        {
            for (int X = 0; X <= UB; X++) {
                if (MatrixArr[X, pNode] == -1) continue;

                WillEnque.FromNode = X;
                WillEnque.ToNode = pNode;
                WillEnque.Cost = MatrixArr[X, pNode];
                InsPQueue.Enqueue(WillEnque);
            }
        };

        EnqueueAct(0);

        // 訪問済ノード
        var VisitedSet = new HashSet<int>();
        VisitedSet.Add(0);

        int Answer = 0;
        while (InsPQueue.IsEmpty() == false) {
            PQueue.PQueueJyoutaiDef Dequed = InsPQueue.Dequeue();

            if (VisitedSet.Contains(Dequed.FromNode) && (VisitedSet.Contains(Dequed.ToNode)))
                continue;

            Answer += Dequed.Cost;

            if (VisitedSet.Contains(Dequed.FromNode) == false) {
                EnqueueAct(Dequed.FromNode);
                VisitedSet.Add(Dequed.FromNode);
            }
            if (VisitedSet.Contains(Dequed.ToNode) == false) {
                EnqueueAct(Dequed.ToNode);
                VisitedSet.Add(Dequed.ToNode);
            }
        }
        Console.WriteLine(Answer);
    }

    static void PrintBan(int[,] pArr)
    {
        for (int Y = 0; Y <= pArr.GetUpperBound(1); Y++) {
            for (int X = 0; X <= pArr.GetUpperBound(0); X++) {
                Console.Write("{0,2},", pArr[X, Y]);
            }
            Console.WriteLine();
        }
    }
}

#region PQueue
// 優先度付きキュー
internal class PQueue
{
    internal struct PQueueJyoutaiDef
    {
        internal int FromNode;
        internal int ToNode;
        internal int Cost;
    }

    private Dictionary<int, PQueueJyoutaiDef> mHeapDict = new Dictionary<int, PQueueJyoutaiDef>();

    internal bool IsEmpty()
    {
        return mHeapDict.Count == 0;
    }

    // エンキュー処理
    internal void Enqueue(PQueueJyoutaiDef pAddJyoutai)
    {
        int CurrNode = 1 + mHeapDict.Count;
        mHeapDict[CurrNode] = pAddJyoutai;

        while (1 < CurrNode && mHeapDict[CurrNode / 2].Cost > mHeapDict[CurrNode].Cost) {
            PQueueJyoutaiDef Swap = mHeapDict[CurrNode];
            mHeapDict[CurrNode] = mHeapDict[CurrNode / 2];
            mHeapDict[CurrNode / 2] = Swap;

            CurrNode /= 2;
        }
    }

    // デキュー処理
    internal PQueueJyoutaiDef Dequeue()
    {
        PQueueJyoutaiDef TopNode = mHeapDict[1];
        int LastNode = mHeapDict.Count;
        mHeapDict[1] = mHeapDict[LastNode];
        mHeapDict.Remove(LastNode);

        MinHeapify(1);
        return TopNode;
    }

    // 根ノードを指定し、根から葉へヒープ構築
    private void MinHeapify(int pRootNode)
    {
        if (mHeapDict.Count <= 1) {
            return;
        }

        int Left = pRootNode * 2;
        int Right = pRootNode * 2 + 1;

        // 左の子、自分、右の子で値が最小のノードを選ぶ
        int Smallest = mHeapDict[pRootNode].Cost;
        int SmallestNode = pRootNode;

        if (mHeapDict.ContainsKey(Left) && mHeapDict[Left].Cost < Smallest) {
            Smallest = mHeapDict[Left].Cost;
            SmallestNode = Left;
        }
        if (mHeapDict.ContainsKey(Right) && mHeapDict[Right].Cost < Smallest) {
            Smallest = mHeapDict[Right].Cost;
            SmallestNode = Right;
        }

        // 子ノードのほうが大きい場合
        if (SmallestNode != pRootNode) {
            PQueueJyoutaiDef Swap = mHeapDict[SmallestNode];
            mHeapDict[SmallestNode] = mHeapDict[pRootNode];
            mHeapDict[pRootNode] = Swap;

            // 再帰的に呼び出し
            MinHeapify(SmallestNode);
        }
    }
}
#endregion


解説

プリム法で解いてます。