baekjoon 11286:절댓값 힙
11286번 절댓값 힙
접근
우선순위 큐 사용해서 하면 될 것 같다. 저번 vector만들 때 썼던 방식처럼
연산자 오버로딩 방식으로 하면 될 것 같다.
코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <queue>
using namespace std;
struct Compare {
bool operator()(int a, int b) const {
if(abs(a) > abs(b)) return true;
else if(abs(a) == abs(b)) return a > b;
else return false;
}
};
int main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int n; cin >> n;
priority_queue<int, vector<int>, Compare> pq;
while(n--){
int x; cin >> x;
if(x == 0){
if(pq.empty()) cout << 0 << '\n';
else{
cout << pq.top() << '\n';
pq.pop();
}
}
else pq.push(x);
}
return 0;
}
배운 점
vector와는 다르게 그냥 비교함수 만들면 안되더라.
priority_queue는 꼭 struct써서 연산자 오버로딩 해야한다더라.
This post is licensed under CC BY 4.0 by the author.