heap이라고 써둬서 쉬웠던 문제.

min heap을 구현하여 계속 반복 하면된다.다만 priority queue 생성을 priority_queue<int, vector<int>, compare> queue(scoville.begin(), scoville.end()); 로 가능하다는걸 알게되었다.

#include <string>
#include <vector>
#include <queue>

using namespace std;

struct compare {
    bool operator()(int a, int b)
    {
        return a > b;
    }
};

int solution(vector<int> scoville, int K) {
    int answer = 0;
    priority_queue<int, vector<int>, compare> queue;
    //priority_queue<int, vector<int>, compare> queue(scoville.begin(), scoville.end());
    int first, second;

    for (int i = 0; i < scoville.size(); i++)
        queue.push(scoville[i]);

    while (queue.top() < K)
    {
        first = queue.top();
        queue.pop();

        if (queue.empty())
            break;

        second = queue.top();
        queue.pop();

        answer++;
        queue.push(first + second * 2);
    }

    if (queue.empty())
        answer = -1;

    return answer;
}

+ Recent posts