Algorithm/백준

[백준] 11286 절댓값 힙 with C++

nowkoes 2023. 5. 23. 00:00

문제설명


입출력 예제


개념

 우선순위 큐의 정렬 순서를 직접 지정하면 풀 수 있는 문제다. 구조체를 이용하여 연산자를 오버로딩하여도 되고, 단순히 비교 함수를 인자로 추가해도 된다.


풀이

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

bool abs_operator(int a, int b)
{
	return abs(a) == abs(b) ? a > b : abs(a) > abs(b);
}

int main()
{
	ios::sync_with_stdio(false); cin.tie(nullptr);
	int N, n;

	priority_queue<int, vector<int>, decltype(&abs_operator)> pq(abs_operator);

	cin >> N;

	while (N--)
	{
		cin >> n;

		if (n == 0)
		{
			if (pq.empty())
				printf("0\n");

			else
			{
				printf("%d\n", pq.top());
				pq.pop();
			}
		}

		else
			pq.push(n);
	}
}

 

반응형