본문 바로가기

코딩테스트/프로그래머스

[프로그래머스] 더 맵게

프로그래머스 더 맵게 C++ 풀이

 

https://programmers.co.kr/learn/courses/30/lessons/42626

 

 

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

using namespace std;

int solution(vector<int> scoville, int K) {
    int answer = 0;

    priority_queue<int, vector<int>, greater<int>> pq(scoville.begin(), scoville.end()); 
    // priority_queue<int> pq와 같다. 내림차순이 default인데 오름차순으로 쓰다 보니까 저렇게 됨
    // priority_queue로 오름차순으로 정렬 priority_queue가 vector형태로 담음 greater은 오름 차순으로 내림차순은 less
    
    while(pq.top() < K){
        
        if(pq.size() == 1) return answer = -1;
        int first = pq.top();
        pq.pop();
        int second = pq.top();
        pq.pop();
        pq.push(first + 2 * second);
        answer++;
    }
    
    return answer;
}