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

ALDS1_9_B: Maximum Heap


問題へのリンク


C#のソース

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

// Q031 最大・最小ヒープ https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_9_B&lang=jp
class Program
{
    static string InputPattern = "InputX";

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

        if (InputPattern == "Input1") {
            WillReturn.Add("10");
            WillReturn.Add("4 1 3 2 16 9 10 14 8 7");
            // 16 14 10 8 7 9 3 2 4 1
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static Dictionary<int, int> mHeapDict = new Dictionary<int, int>();

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

        int[] wkArr = InputList[1].Split(' ').Select(X => int.Parse(X)).ToArray();

        for (int I = 0; I <= wkArr.GetUpperBound(0); I++) {
            mHeapDict[I + 1] = wkArr[I];
        }

        int H = mHeapDict.Keys.Max();
        for (int I = H; 1 <= I; I--) {
            MaxHeapify(I);
        }

        foreach (var EachPair in mHeapDict.OrderBy(pX => pX.Key)) {
            Console.Write(" {0}", EachPair.Value);
        }
        Console.WriteLine();
    }

    static void MaxHeapify(int pRootNode)
    {
        int Left = pRootNode * 2;
        int Right = pRootNode * 2 + 1;

        // 左の子、自分、右の子で値が最大のノードを選ぶ
        int Largest = mHeapDict[pRootNode];
        int LargestNode = pRootNode;

        if (mHeapDict.ContainsKey(Left) && mHeapDict[Left] > Largest) {
            Largest = mHeapDict[Left];
            LargestNode = Left;
        }
        if (mHeapDict.ContainsKey(Right) && mHeapDict[Right] > Largest) {
            Largest = mHeapDict[Right];
            LargestNode = Right;
        }

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

            // 再帰的に呼び出し
            MaxHeapify(LargestNode);
        }
    }
}


解説

疑似コードをC#で実装してます。