백준/1000 ~
[백준 / C#] 1927 : 최소 힙
무오_
2023. 7. 24. 18:44
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace _11279
{
class MaxHeap
{
private List<int> A = new List<int>();
public void Add(int value)
{
// Add the end
A.Add(value);
// bubble up(부모노드 찾기)
int i = A.Count - 1;
while (i > 0)
{
int parent = (i - 1) / 2;
if (A[parent] > A[i]) // Max Heap일때는 부등호를 반대
{
Swap(parent, i);
i = parent;
}
else break;
}
}
public int RemoveOne()
{
if (A.Count.Equals(0))
return 0;
//Min Heap
int root = A[0];
A[0] = A[A.Count - 1];
A.RemoveAt(A.Count - 1);
// bubble down
int i = 0;
int last = A.Count - 1;
while (i < last)
{
int child = i * 2 + 1;
if (child < last &&
A[child] > A[child + 1]) //Max Heap일때는 반대
child = child + 1;
if (child > last ||
A[i] <= A[child]) //Max Heap일때는 반대
break;
Swap(i, child);
i = child;
}
return root;
}
private void Swap(int i, int j)
{
int t = A[i];
A[i] = A[j];
A[j] = t;
}
}
class Program
{
static int n;
static StringBuilder sb = new StringBuilder();
static MaxHeap item = new MaxHeap();
static void Solution(int n)
{
if (n.Equals(0))
sb.AppendLine(item.RemoveOne().ToString());
else item.Add(n);
}
static void Input()
{
StreamReader sr = new StreamReader(Console.OpenStandardInput());
n = int.Parse(sr.ReadLine());
for (int i = 0; i < n; i++)
Solution(int.Parse(sr.ReadLine()));
Console.WriteLine(sb);
}
static void Solve()
{
Input();
}
static void Main(string[] args)
{
Solve();
}
}
}