프로그래머스/Level_2

[Level_2] 더 맵게 (C++)

배발자 2022. 1. 17.
반응형
 

<priority_queue> 자료구조

 Priority_Queue는 Queue 의 한 종류인데 말 그대로 우선순위에 따라 정렬된 Queue라고 보면 도니다. 와 동일한 라이브러리에서 지원 해주며 특정 원소를 push 를 할 때 O(logN)만에 이루어진다. 해당 시간

baebalja.tistory.com


해당 문제는 priority_queue 를 알면 쉽게 풀 수 있다. 

값을 삽입 할 때 오름차순으로 정렬 되어있는 min heap으로 생성해준다. 

그렇게 한다면 최소값이 루트노드에 위치하게 되며 제일 작은 값을 우선적으로 pop을 해주기 때문에 해당 문제를 쉽게 풀 수 있다. 

#include <string>
#include <vector>
#include <queue> 
using namespace std;

int solution(vector<int> scoville, int K) {
    int answer = 0;
    priority_queue<int, vector<int>, greater<int>> q; 
    for(int x : scoville){
        q.push(x); 
    }
    int cnt =0; 
    while(!q.empty()){
        int a = q.top(); 
        if(a>=K)return cnt; 
        cnt++; 
        q.pop(); 
        if(q.empty())return -1; 
        int b= q.top(); 
        q.pop(); 
        a = a+ 2*b; 
        q.push(a);         
    }    
    return cnt;
}

 

 

코딩테스트 연습 - 더 맵게

매운 것을 좋아하는 Leo는 모든 음식의 스코빌 지수를 K 이상으로 만들고 싶습니다. 모든 음식의 스코빌 지수를 K 이상으로 만들기 위해 Leo는 스코빌 지수가 가장 낮은 두 개의 음식을 아래와 같

programmers.co.kr

 

 

반응형

댓글