๐Ÿ“ Coding Test Study/Algorithm Problem

[C++][ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค][Heap] ๋” ๋งต๊ฒŒ

ibelieveinme 2021. 9. 22. 16:31
728x90

[๋ฌธ์ œ]

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋” ๋งต๊ฒŒ

๋งค์šด ๊ฒƒ์„ ์ข‹์•„ํ•˜๋Š” Leo๋Š” ๋ชจ๋“  ์Œ์‹์˜ ์Šค์ฝ”๋นŒ ์ง€์ˆ˜๋ฅผ K ์ด์ƒ์œผ๋กœ ๋งŒ๋“ค๊ณ  ์‹ถ์Šต๋‹ˆ๋‹ค. ๋ชจ๋“  ์Œ์‹์˜ ์Šค์ฝ”๋นŒ ์ง€์ˆ˜๋ฅผ K ์ด์ƒ์œผ๋กœ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด Leo๋Š” ์Šค์ฝ”๋นŒ ์ง€์ˆ˜๊ฐ€ ๊ฐ€์žฅ ๋‚ฎ์€ ๋‘ ๊ฐœ์˜ ์Œ์‹์„ ์•„๋ž˜์™€ ๊ฐ™

programmers.co.kr

์Šค์ฝ”๋นŒ ์ง€์ˆ˜๊ฐ€ ๊ฐ€์žฅ ๋‚ฎ์€ ๋‘๊ฐ€์ง€ ์Œ์‹์„ ์„ž์–ด์„œ ๋ชจ๋“  ์Œ์‹์ด K์ด์ƒ์˜ ์Šค์ฝ”๋นŒ ์ง€์ˆ˜๋ฅผ ๊ฐ€์ง€๊ฒŒ ํ•˜๋ ค ํ•  ๋•Œ ํ•„์š”ํ•œ ์ตœ์†Œ ์—ฐ์‚ฐ ํšŸ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ๊ฒƒ.

 

[ํ’€์ด]

์ฒ˜์Œ์—” ๊ฑ STL algorithm์˜ sort() ํ•จ์ˆ˜๋กœ scoville ๋ฒกํ„ฐ๋ฅผ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌํ•˜๊ณ  scoville ๋ฒกํ„ฐ์˜ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’๊ณผ ๋‘๋ฒˆ์งธ๋กœ ์ž‘์€ ๊ฐ’์„ K๋ณด๋‹ค ์ปค์งˆ ๋•Œ๊นŒ์ง€ ์—ฐ์‚ฐํ•˜๋Š” ๊ณผ์ •์„ ๋ฐ˜๋ณตํ–ˆ๋‹ค. ๊ฒฐ๊ณผ๋Š” ํšจ์œจ์„ฑ ํ…Œ์ŠคํŠธ 0์ .

#include <vector>
#include <algorithm>
using namespace std;

int solution(vector<int> scoville, int K) { // scoville: 2 ์ด์ƒ 1,000,000 ์ดํ•˜
    int answer = 0;

    int first_low_scoville = 0;
    int second_low_scoville = 0;
    
    sort(scoville.begin(), scoville.end(), greater<int>()); //๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ
    
    while(scoville.back() < K){
        if(scoville.size() < 2) return -1;

        first_low_scoville = scoville.back();
        scoville.pop_back();
        second_low_scoville = scoville.back();
        scoville.pop_back();
        
        scoville.push_back(first_low_scoville + (second_low_scoville*2));
        sort(scoville.begin(), scoville.end(), greater<int>()); //๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ
        
        answer++;
    }
    return answer;
}

 

๋ฌธ์ œ ์œ ํ˜•์— ๋งž๊ฒŒ Heap ์ž๋ฃŒ๊ตฌ์กฐ(Priority queue)๋ฅผ ์ด์šฉํ•ด์„œ ์‹œ๊ฐ„์„ ๋‹จ์ถ•์‹œ์ผœ์•ผ ํ–ˆ๋‹ค.

 

priority queue๋Š” root์— ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์ด ๋†“์ด๋Š” ์™„์ „ ์ด์ง„ ํŠธ๋ฆฌ ๊ตฌ์กฐ๋ฅผ ๊ฐ–๋Š”๋‹ค. ์™„์ „ ์ด์ง„ ํŠธ๋ฆฌ ๊ตฌ์กฐ์ด๋ฏ€๋กœ ์‚ฝ์ž…/์‚ญ์ œ/ํƒ์ƒ‰ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ O(logN)๋กœ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค. ๊ทธ๋ž˜์„œ ์ด ๋ฌธ์ œ์ฒ˜๋Ÿผ ๋น ๋ฅด๊ฒŒ ์ตœ์†Œ๊ฐ’/์ตœ๋Œ€๊ฐ’์„ ์ฐพ์•„์•ผ ํ•  ๋•Œ ์œ ์šฉํ•˜๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. 

 

[์ฝ”๋“œ]

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

int solution(vector<int> scoville, int K) { // scoville: 2 ์ด์ƒ 1,000,000 ์ดํ•˜
    int answer = 0;
    
    int first_low_scoville;
    int second_low_scoville;
    
    priority_queue<int, vector<int>, greater<int>> pq(scoville.begin(), scoville.end());
    
    while(pq.top() < K){
        if(pq.size() <=1 ) return -1;
        
        first_low_scoville = pq.top();
        pq.pop();
        second_low_scoville = pq.top();
        pq.pop();

        pq.push(first_low_scoville + second_low_scoville*2);
        answer++;
    }
    
    return answer;
}

 

 

 

728x90