[백준 실버1] 11286 절댓값 힙

수민이슈·2023년 9월 13일
0

[C++] 코딩테스트

목록 보기
58/116
post-thumbnail

🖊️ 문제

https://www.acmicpc.net/problem/11286


🖊️ 풀이

그냥 보자마자 priority_queue 사용해서 푸는 문제인데, 절댓값과 원래 값을 모두 저장해야 해서 pair를 넣고 풀었다.

pq 내의 비교 연산은 구조체 연산자 오버로딩을 통해 구현했다

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

struct Compare {
	bool operator() (pair<int, int>& a, pair<int, int>& b) {
		if (a.second == b.second) return a.first > b.first;
		else return a.second > b.second;
	}
};

int main()
{
	cin.tie(0);
	cout.tie(0);
	ios::sync_with_stdio(false);

	int N;
	cin >> N;

	int num;
	priority_queue<pair<int, int>, vector<pair<int, int>>, Compare> pq;
	for (int i = 0; i < N; i++) {
		cin >> num;
		if (num == 0) {
			if (pq.empty()) cout << 0 << '\n';
			else {
				cout << pq.top().first << '\n';
				pq.pop();
			}
		}
		else {
			pq.push(make_pair(num, abs(num)));
		}
	}
}

0개의 댓글