[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
๋ฐ์ํ
'Coding Test > Programmers' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Programmers] Lv2. ์คํ์ฑํ ๋ฐฉ | C++ (0) | 2023.06.21 |
---|---|
[Programmers] Lv2. [3์ฐจ] n์ง์ ๊ฒ์ | C++ (0) | 2023.06.21 |
[Programmers] Lv2. k์ง์์์ ์์ ๊ฐ์ ๊ตฌํ๊ธฐ | C++ (0) | 2023.06.21 |
[Programmers] Lv2. ํ๊ฒ ๋๋ฒ | C++ (0) | 2023.06.20 |
[Programmers] Lv2. ๋ด์ค ํด๋ฌ์คํฐ๋ง | C++ (0) | 2023.06.20 |