๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿš“ Self Study/๐Ÿ”“ Programmers

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค (๋” ๋งต๊ฒŒ, ํž™(Heap)) C++

by UKHYUN22 2022. 1. 1.
728x90

 

// ๊ธฐ๋ณธ์ ์œผ๋กœ ๋งŒ๋“ค์–ด์ง€๋Š” ํ๊ฐ€ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ์ด ๋œ๋‹ค.
Priority_queue <int> pq;

// ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ๋ฒกํ„ฐ๋ฅผ ์ •๋ ฌํ•  ๋•Œ
Priority_queue<int, vector<int>, greater<int>> pq;

// ์šฐ์„ ์ˆœ์œ„ ํ์˜ ์›์†Œ ์‚ฝ์ž…
pq.push(์›์†Œ);

// ์šฐ์„ ์ˆœ์œ„์˜ ๊ฐ€์žฅ ์•ž์˜ ์›์†Œ ํ™•์ธ
pq.top();

// ์šฐ์„ ์ˆœ์œ„์˜ ๊ฐ€์žฅ ์•ž์˜ ์›์†Œ ์ œ๊ฑฐ
pq.pop();

// ํฌ๊ธฐ ํ™•์ธ ๋ฐ ๋น„์–ด์žˆ๋Š”์ง€ ์œ ๋ฌด
pq.size();
pq.empty();

 

์šฐ์„ ์ˆœ์œ„ ํ๋ฅผ ์“ฐ์ง€ ์•Š๊ณ ๋Š” ์ •๋‹ต์ฒ˜๋ฆฌ๊ฐ€  ๋˜์ง€ ์•Š๋Š” ๋ฌธ์ œ์˜€๋‹ค. ๊ธฐ์กด์—๋Š” sort๋ฅผ ์ด์šฉํ•ด์„œ while ๋ฌธ ์•ˆ์—์„œ ๊ณ„์†์ ์œผ๋กœ ์ •๋ ฌ์„ ์‹œ์ผœ์คฌ๋Š”๋ฐ ์ด๋Š” ํšจ์œจ์„ฑ ์ธก๋ฉด์—์„œ ์ข‹์ง€ ์•Š์Œ์„ ๋ฐฐ์šธ ์ˆ˜ ์žˆ์—ˆ๋‹ค. priority_queue๋ฅผ ์„ ์–ธํ•˜๋ฉด ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ž๋™ ์ •๋ ฌ๋˜๊ณ  ์ด๋ฅผ ์ด์šฉํ•ด topํ™•์ธpop ์ œ๊ฑฐ push ์ถ”๊ฐ€๋ฅผ ํ•œ๋‹ค๋ฉด ๋”์šฑ์ด ํšจ์œจ์ ์ธ ์ฝ”๋“œ๊ฐ€ ๋  ๊ฒƒ์ด๋‹ค.

 

#include <string>
#include <vector>
#include <queue>
#include <iostream>

using namespace std;

int solution(vector<int> scoville, int K) {
    int answer = 0;
    
    priority_queue <int, vector<int>, greater<int>> p_queue (scoville.begin(), scoville.end());
    
    while(p_queue.size() > 1 && p_queue.top() < K) {
        int first = p_queue.top();
        p_queue.pop();
        
        int second = p_queue.top();
        p_queue.pop();
        
        int new_sco = first + second * 2;
        p_queue.push(new_sco);
        
        answer++;
    }
    
    if(p_queue.top() < K) return -1;
    
    return answer;
}

 

 

์ด๋Š” ๋‚ด๊ฐ€ ์šฐ์„ ์ˆœ์œ„ ํ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•˜์„ ๋•Œ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋ฅผ ํ†ต๊ณผํ•œ ์ฝ”๋“œ์ด๋‹ค

 

 

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

int solution(vector<int> scoville, int K) {
    int answer = 0;
    int new_sco = 0;
    
    while(true) {
        int count = 0;
        
        for(int i = 0 ; i < scoville.size() ; i++) {
            if(scoville[i] >= K) count++;
        }
        
        if(count == scoville.size()) break;
        
        sort(scoville.begin(), scoville.end());
        
        new_sco = scoville[0] + scoville[1] * 2;
        scoville.erase(scoville.begin());
        scoville[0] = new_sco;
        
        
        answer++;
    }
    
    return answer;
}