[프로그래머스/C++]Lv.2 - 더 맵게

YH J·2023년 10월 4일
0

프로그래머스

목록 보기
162/168

문제 링크

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

내 풀이

처음엔 set사용했다가 중복허용안되는걸 아차하고 priority queue를 사용했다.
scoville를 큐에 옮겨담는다.
큐는 오름차순으로 정렬해준다 ( priority_queue의 기본 정렬 순서는 내림차순 )
이미 top이 K를 넘으면 0을 리턴해준다.
while을 돌리면서 top을 가져오고 pop해주고 top을 가져오고 pop해줘서 가장 작은 2개의 값을 얻어서 스코빌 지수 계산 후 push해준다.
top을 검사해서 K이상이면 count를 return 해준다.
while을 전부 돌리고도 K이상이 아니면 -1 이 리턴된다.

내 코드

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

int solution(vector scoville, int K) {
int answer = -1;

priority_queue<int, vector<int>, greater<int>> pq;

for(const int& sc : scoville)
    pq.push(sc);

if(pq.top() >= K)
    return 0;

int count = 0;
int a = 0;
int b = 0;

while(pq.size() >= 2)
{       
    a = pq.top();
    pq.pop();
    b = pq.top();
    pq.pop();      
    pq.push(a + b*2);
    
    count++;
    if(pq.top() >= K)
        return count;
}

return answer;

}


## 다른 사람의 풀이

```cpp
#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>> tmpl;
    for(const auto& v : scoville)
        tmpl.push(v);
    auto first_min_value = tmpl.top();
    while((tmpl.size() > 1) && (first_min_value < K))
    {
        tmpl.pop();
        auto second_min_value = tmpl.top();
        tmpl.pop();
        auto new_scoville = first_min_value + (second_min_value * 2);
        tmpl.push(new_scoville);
        ++answer;
        first_min_value = tmpl.top();
    }
    
    if((answer == 0) || (first_min_value < K))         answer = -1;
    return answer;
}

다른 사람의 풀이 해석

같은 방법이다.

profile
게임 개발자 지망생

0개의 댓글