반응형
https://www.acmicpc.net/problem/7662
문제 해결 알고리즘
최대 힙과 최소 힙으로 각각 최댓값 최솟값을 알아내고, map을 이용해서 남아있는 원소들의 갯수를 저장해준다.
없으면 힙에서 삭제를 해주어야한다.
오버플로우가 나므로 long long 자료형을 써주어야한다.
소스 코드
#include <bits/stdc++.h>
#define ll long long
using namespace std;
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
int T; cin >> T;
while(T--){
priority_queue<ll> max_heap;
priority_queue<ll> min_heap;
map<ll, ll> heap_map;
int heap_size = 0;
ll k; cin >> k;
for(int i=0;i<k;i++){
char a; ll b; cin >> a >> b;
if(a == 'I'){
max_heap.push(b); min_heap.push(-b);
heap_size ++;
if(heap_map.count(b) != 0) heap_map[b]++;
else heap_map[b] = 1;
}
if(a == 'D'){
if(heap_size == 0) continue;
if(b == 1) {
while (!max_heap.empty() && heap_map[max_heap.top()] == 0) max_heap.pop();
if(!max_heap.empty()){
heap_map[max_heap.top()] --;
max_heap.pop();
}
}
else {
while (!min_heap.empty() && heap_map[-min_heap.top()] == 0) min_heap.pop();
if(!min_heap.empty()){
heap_map[-min_heap.top()] --;
min_heap.pop();
}
}
heap_size --;
}
}
while (!max_heap.empty() && heap_map[max_heap.top()] == 0) max_heap.pop();
while (!min_heap.empty() && heap_map[-min_heap.top()] == 0) min_heap.pop();
if(max_heap.empty() || min_heap.empty()) cout << "EMPTY\n";
else cout << max_heap.top() << ' ' << -min_heap.top() << '\n';
}
}
반응형
'알고리즘 문제 해결 > BOJ' 카테고리의 다른 글
[0-1 BFS] BOJ 1261 알고스팟 (C++) (0) | 2022.10.17 |
---|---|
[0-1 BFS] BOJ 13549 숨바꼭질 3 (C++) (0) | 2022.10.14 |
[백트래킹] BOJ 1062 가르침 (C++) (0) | 2022.10.08 |
[DP] BOJ 7579 앱 (C++) (0) | 2022.10.05 |
[DP] BOJ 11062 카드 게임 (C++) (0) | 2022.10.02 |