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

xyzw·2025년 2월 13일
0

algorithm

목록 보기
25/61

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

풀이

문제에서 요구하는 기준을 만족하도록 우선순위 큐의 비교함수를 직접 만들었다.

우선순위 커스텀

struct cmp {
	bool operator() (const 자료형 &x1, const 자료형 &x2) {
    	...
    }
};

위 구조체를 사용하면 된다.

코드

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

struct cmp {
    bool operator()(int &a, int &b){
        if(abs(a) != abs(b)) return abs(a) > abs(b);
        return a > b;
    }
};

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    
    int n, x;
    cin >> n;
    
    priority_queue<int, vector<int>, cmp> heap;
    while(n--){
        cin >> x;
        
        if(x == 0) {
            if(heap.empty()) cout << "0\n";
            else {
                cout << heap.top() << "\n";
                heap.pop();
            }
        }
        else heap.push(x);
    }
    
    return 0;
}

0개의 댓글