[Programmers] Lv2. 더 맡게 | C++

2023. 6. 21. 16:23ㆍCoding Test/Programmers

πŸ”—λ¬Έμ œ λ³΄λŸ¬κ°€κΈ°
 

ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€

μ½”λ“œ μ€‘μ‹¬μ˜ 개발자 μ±„μš©. μŠ€νƒ 기반의 ν¬μ§€μ…˜ 맀칭. ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€μ˜ 개발자 λ§žμΆ€ν˜• ν”„λ‘œν•„μ„ λ“±λ‘ν•˜κ³ , λ‚˜μ™€ 기술 ꢁ합이 잘 λ§žλŠ” 기업듀을 맀칭 λ°›μœΌμ„Έμš”.

programmers.co.kr

 

πŸ‘¨‍πŸ’»ν’€μ΄ κ³Όμ •

 

문제 μœ ν˜•λ„ νž™(Heap)이라 λΆ„λ₯˜λ˜μ–΄ μžˆμ—ˆμ§€λ§Œ, 지문을 읽자마자 μ΅œμ†Œ νž™(Min Heap)이 μƒκ°λ‚˜λŠ” λ¬Έμ œμ˜€μŠ΅λ‹ˆλ‹€. μž…λ ₯ λ²”μœ„ μˆ«μžκ°€ 맀우 ν¬λ―€λ‘œ, μ˜€λ²„ν”Œλ‘œμš°λ§Œ μ‘°μ‹¬ν•˜λ©΄ μ†μ‰½κ²Œ ν’€ 수 μžˆμ—ˆμŠ΅λ‹ˆλ‹€.

 

βœοΈμ†ŒμŠ€ μ½”λ“œ 및 κ²°κ³Ό

#include <string>
#include <vector>
#include <queue>
using namespace std;
using LL = long long;

int solution(vector<int> scoville, int K) {
    int answer = 0;
    priority_queue<LL, vector<LL>, greater<LL>> scovilles;
    
    for (const auto element : scoville)
        scovilles.emplace(element);
    

    while (scovilles.size() >= 2) {
        LL leastSpicyFood = scovilles.top();
        scovilles.pop();

        LL secondLeastSpicyFood = scovilles.top();
        scovilles.pop();

        if (leastSpicyFood >= K)
            break;

        LL newScovill = leastSpicyFood + secondLeastSpicyFood * 2;
        answer++;
        scovilles.emplace(newScovill);
    }

    if (scovilles.top() < K)
        return -1;

    return answer;
}

 

 

728x90
λ°˜μ‘ν˜•