競技プログラミングの鉄則
次の問題へ
前の問題へ
A53 Priority Queue
C#のソース
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static string InputPattern = "InputX";
static List<string> GetInputList()
{
var WillReturn = new List<string>();
if (InputPattern == "Input1") {
WillReturn.Add("3");
WillReturn.Add("1 2420");
WillReturn.Add("1 1650");
WillReturn.Add("2");
//1650
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static void Main()
{
List<string> InputList = GetInputList();
var InsPQueue = new PQueue();
foreach (string EachStr in InputList.Skip(1)) {
string[] SplitArr = EachStr.Split(' ');
if (SplitArr[0] == "1") {
long X = long.Parse(SplitArr[1]);
PQueue.PQueueJyoutaiDef WillEnque;
WillEnque.Val = X;
InsPQueue.Enqueue(WillEnque);
}
if (SplitArr[0] == "2") {
long PeekVal = InsPQueue.Peek();
Console.WriteLine(PeekVal);
}
if (SplitArr[0] == "3") {
InsPQueue.Dequeue();
}
}
}
}
#region PQueue
// 優先度付きキュー (根のValが最小)
internal class PQueue
{
internal struct PQueueJyoutaiDef
{
internal long Val;
}
private Dictionary<int, PQueueJyoutaiDef> mHeapDict = new Dictionary<int, PQueueJyoutaiDef>();
internal bool IsEmpty()
{
return mHeapDict.Count == 0;
}
internal long Count()
{
return mHeapDict.Count;
}
internal long Peek()
{
return mHeapDict[1].Val;
}
// エンキュー処理
internal void Enqueue(PQueueJyoutaiDef pAddJyoutai)
{
int CurrNode = 1 + mHeapDict.Count;
mHeapDict[CurrNode] = pAddJyoutai;
while (1 < CurrNode && mHeapDict[CurrNode / 2].Val > mHeapDict[CurrNode].Val) {
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;
// 左の子、自分、右の子で値が最小のノードを選ぶ
long Smallest = mHeapDict[pRootNode].Val;
int SmallestNode = pRootNode;
if (mHeapDict.ContainsKey(Left) && mHeapDict[Left].Val < Smallest) {
Smallest = mHeapDict[Left].Val;
SmallestNode = Left;
}
if (mHeapDict.ContainsKey(Right) && mHeapDict[Right].Val < Smallest) {
Smallest = mHeapDict[Right].Val;
SmallestNode = Right;
}
// 子ノードのほうが小さい場合
if (SmallestNode != pRootNode) {
PQueueJyoutaiDef Swap = mHeapDict[SmallestNode];
mHeapDict[SmallestNode] = mHeapDict[pRootNode];
mHeapDict[pRootNode] = Swap;
// 再帰的に呼び出し
MinHeapify(SmallestNode);
}
}
}
#endregion
解説
ライブラリのプライオリティキューを使ってます。