본문 바로가기

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

[프로그래머스] 더 맵게

728x90
반응형


🔗 문제 링크

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


728x90

👩‍💻 코드

#include <string>
#include <vector>
#include <algorithm>
#include <functional>

using namespace std;

int solution(vector<int> scoville, int K) {
    int answer = 0;
    vector<int> heap = scoville;
    
    make_heap(heap.begin(), heap.end(), greater<int>());
    
    while(!heap.empty()){
        int min1 = heap.front();
        
        if(min1 >= K){
            return answer;
        }
        
        pop_heap(heap.begin(), heap.end(), greater<int>());
        heap.pop_back();
        
        if(heap.empty()){
            return min1 >= K ? answer : -1;
        }
        
        int min2 = heap.front();
        pop_heap(heap.begin(), heap.end(), greater<int>());
        heap.pop_back();
        
        heap.push_back(min1 + min2 * 2);
        push_heap(heap.begin(), heap.end(), greater<int>());
        
        answer++;
    }
    
    return answer;
}

📝 풀이

주어진 스코빌 지수 vector<int>로 최소 힙을 만듭니다.

최소값이 K이상이면 answer을 return 합니다.

최소값을 heap에서 pop하고 이 때 힙이 비어있고 최소값이 K 미만이면 -1을 return 합니다.

두 번째 최소값도 heap에서 pop하고 최소값과 두 번째 최소값을 섞어 새로운 음식을 만듭니다.

새로 만든 음식은 heap에 push하고 섞은 횟수(answer)을 증가시킵니다.

 

지금 보니 반복문의 조건을 잘못 설정한거 같습니다...😅

728x90
반응형