힙구조를 사용하여 모든 음식의 스코빌 지수를 K 이상으로 만드는 것

 

힙구조는 priority_queue 를 사용하여 구현

※priority_queue에서 정렬를 부여해두려면 priority_queue<자료형, 구현체, 비교연산자> 로 우선순위 큐를 선언하면 된다. 

지금은 오름차순으로 정렬해야하니 priority_queue<int,vector<int>,greater<int>> pq 로 선언해 두었다.

 

#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;          //정렬 조건 오름차순으로
    
    for(int i=0;i<scoville.size();i++){
        pq.push(scoville[i]);
    }
    
    while(pq.size()>=2&&pq.top()<K){
        int first=pq.top();
        pq.pop();
        
       int second=pq.top();
        pq.pop();
        
        answer++;
        pq.push(first+second*2);
    }
    
    if(!pq.empty()&&pq.top()<K) return -1;
    
    return answer;
}

+ Recent posts