[백준] 1927 최소 힙 / 우선순위 큐 (C++)

sobokii·2023년 10월 25일
0

문제풀이

목록 보기
31/52

최소 힙 구현하기

나는 처음에 이렇게 풀었다.

#include <iostream>
#include <queue>
using namespace std;

struct Number
{
	int a;

	Number(int n)
	{
		a = n;
	}
	bool operator<(const Number &b) const
	{
		return a > b.a;
	}
};

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	
	priority_queue<Number> pQ;
	int N;
	cin >> N;

	for (int i = 0; i < N; i++)
	{
		int x;
		cin >> x;

		if (x == 0)
		{
			if (pQ.empty())
			{
				cout << 0 << "\n";
			}
			else
			{
				cout << pQ.top().a << "\n";
				pQ.pop();
			}			
		}
		else
		{
			pQ.push(Number(x));
		}		
	}

	return 0;
}

그러나 더 쉬운 방법이 있더라

priority_queue<int, vector<int>, greater<int>> pQ;

이렇게 하면 최소 힙...!

priority_queue pQ; 이렇게 하면 내림차순 정렬해주는 우선순위 큐 만들어주고

priority_queue<int, vector> pQ; 이렇게 해도 내림차순 정렬 우선순위 큐

priority_queue<int, vector, greator> pQ; 이렇게하면 오름차순 정렬 우선순위 큐

profile
직장 구하고 있습니다.

0개의 댓글