[백준] 1927 - 최소 힙
1. 문제
2. 개요
최소 힙을 이용하여 다음과 같은 연산을 지원하는 프로그램을 만드는 문제.
- 배열에 자연수 x를 넣는다.
- 배열에서 가장 작은 값을 출력하고, 그 값을 배열에서 제거한다.
x가 0인 경우, 최소 값을 출력하고 빼낸다. 배열이 비어있는 경우 0을 출력한다.
3. 풀이 및 코드
3-1. 풀이
파이썬의 경우 heapq이 기본적으로 최소 힙이므로 이를 활용한다.
C#의 경우는 우선순위 큐를 이용해 구현한다.
3-2. Python
import sys
import heapq
N = int(sys.stdin.readline())
nums = []
for i in range(N):
command = int(sys.stdin.readline())
if command > 0:
heapq.heappush(nums, command)
elif len(nums) == 0:
print(0)
else:
print(heapq.heappop(nums))
3-3. C#
namespace boj_1927
{
internal class Program
{
static void Main(string[] args)
{
StreamReader sr = new StreamReader(Console.OpenStandardInput());
StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());
int N = int.Parse(sr.ReadLine());
PriorityQueue<int, int> nums = new PriorityQueue<int, int>();
for (int i = 0; i < N; i++)
{
int commnad = int.Parse(sr.ReadLine());
if (commnad > 0)
nums.Enqueue(commnad, commnad);
else if (nums.Count == 0)
sw.WriteLine(0);
else
sw.WriteLine(nums.Dequeue());
}
sw.Close();
}
}
}
Comments