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;
}
'Coding_Test 연습 > Programmers' 카테고리의 다른 글
[프로그래머스] (C++) LV2 짝지어 제거하기 (0) | 2022.05.18 |
---|---|
[프로그래머스] (C++) LV2 타겟 넘버 (0) | 2022.05.18 |
[프로그래머스] (C++) LV2 기능개발 (0) | 2022.04.28 |
[프로그래머스] (C++) LV2 124 나라의 숫자 (0) | 2022.04.28 |
[프로그래머스] (C++) LV2 멀쩡한 사각형 (0) | 2022.04.28 |