[BOJ/C++] 11286 절댓값

GamzaTori·2024년 6월 21일

Algorithm

목록 보기
15/133

우선순위 큐를 이용해 문제를 해결할 수 있습니다.

  1. x==0
    • 큐가 비어있을 때는 0을 출력하고 비어 있지 않을 때는 절댓값이 최소인 값을 출력한다.
    • 단, 절댓값이 같을 경우 음수를 우선하여 출력해야하기 때문에 비교하는 compare 구조체를 따로 정의해야한다.
  2. x==1
    • 우선순위 큐에 값을 추가한다.
// boj s1 11286
// 절댓값 힙

#include <iostream>
#include <queue>

using namespace std;

struct compare
{
	bool operator()(int o1, int o2)
	{
		int first_abs = abs(o1);
		int second_abs = abs(o2);

		if (first_abs == second_abs)
			return o1 > o2;
		else
			return first_abs > second_abs;
	}
};

int main(void)
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	
	int N;
	priority_queue<int, vector<int>, compare> pq;
	cin >> N;

	for (int i = 0; i < N; i++)
	{
		int input;
		cin >> input;
		if (input == 0)
		{
			if (pq.empty())
				cout << 0 << '\n';
			else
			{
				cout << pq.top() << '\n';
				pq.pop();
			}
		}
		else
		{
			pq.push(input);
		}
	}

	return 0;
}
profile
게임 개발 공부중입니다.

0개의 댓글