[C++/PGS] Lv.3 : ๋์คํฌ ์ปจํธ๋กค๋ฌ (Heap/priority_queue)
https://school.programmers.co.kr/learn/courses/30/lessons/42627#
ํ๋ก๊ทธ๋๋จธ์ค
SW๊ฐ๋ฐ์๋ฅผ ์ํ ํ๊ฐ, ๊ต์ก, ์ฑ์ฉ๊น์ง Total Solution์ ์ ๊ณตํ๋ ๊ฐ๋ฐ์ ์ฑ์ฅ์ ์ํ ๋ฒ ์ด์ค์บ ํ
programmers.co.kr
ํ๋ก๊ทธ๋๋จธ์ค ๋ ๋ฒจ 3.
SJF ์ค์ผ์ค๋ง ๊ธฐ๋ฒ์ ๊ตฌํํ๋ ๋ฌธ์ ์ด๋ค!
์๊ฐ๋ณด๋ค ๊น๋ค๋กญ๊ณ , ํ ์ ๋ ฌ ์ปค์คํ ๊ด๋ จํ ๋ฌธ๋ฒ์ ์๊ณ ์์ด์ผ ํด์ ์ฝ๊ฐ ์ด๋ ค์ ๋ค
์ฐ์ ์์์ ๋ฐ๋ผ์ ์๋ ์ ๋ ฌ์ด ๋์ด์ผํ๋๋ฐ, ๊ทธ๋์ ์ฒ์์๋ ์ ๋ ฌ์ด ๊ฐ๋ฅํ Map์ผ๋ก ํ๋ค๊ฐ
์๊ฐ์ด ๋ ๋๋ง๋ค ๊ฐ๋ฅํ ์์ ์ ์ฝ์ ํด์ฃผ๋ ํ์์ด ๋ง๋ค๋ ๊ฑธ ๊นจ๋ฌ์์ Queue๋ก ๋ฐ๊พธ์๋ค.
์ฐ์ ์์ ํ๋ฅผ ์ฌ์ฉํด์, ํด๋น ์๊ฐ์ด ๋ ๋๋ง๋ค ๋ฐ์ดํฐ๋ฅผ ์ฝ์ ํ๊ณ ๊ธฐ์ค์ ๋ง๊ฒ ์ ๋ ฌํด์ผ ํ๋ค!
๋ฐ์ดํฐ ํฌ๊ธฐ๋ ์๊ฐ ๊ฐ์ ๋ํ ์กฐ๊ฑด ๋ฑ์ด ๊ทธ๋ ๊ฒ ํฌ์ง ์์์,
๋ฐ๋ณต๋ฌธ์ ๋๋ฆด ๋๋ง๋ค 1์ด์ฉ ํ๋ฅธ๋ค๊ณ ๊ฐ์ ํ๊ณ ํ์๋ค.
priority_queue๋ฅผ ์ ์ธํ ๋,
์ผ๋ฐ์ ์ธ ์ต๋ ํ ์ฌ์ฉ ์์๋ "priority_queue<vector<int>>" ๋ก ์ฌ์ฉํ๋ฉด ๋๋๋ฐ
์ต์ ํ์ ์ธ ๋๋ ์ ๋ ฌํจ์๋ฅผ ์ปค์คํ ํ๋ ค๋ฉด
"priority_queue<vector<int>, vector<vector<int>>, compare>"
์ด๋ ๊ฒ ๋ณต์กํ๊ฒ ์จ์ผํ๋ ๊ฑธ ์ฒ์ ์์๋ค.
์ ๊ทธ๋ฌ๋ ํ๋๋, ๊ฐ์ ๋ด์์ ์ ๋ ฌํ ์ปจํ ์ด๋๊ฐ ํ์ํ ๊ฑฐ์๋ค,,, ใ .ใ
๊ธฐ์ตํด๋๊ธฐ!!
๋์ ํ์ด
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
#include <iostream>
using namespace std;
struct cmp{
bool operator()(vector<int> &a, vector<int> &b){
if(a[0]==b[0]) return a[1] > b[1];
return a[0] > b[0];
}
// ๋ฐ๊ฟ๋?๋ผ๊ณ ๋ฌผ์ ๋, true -> ๋ฐ๊พผ๋ค
};
int solution(vector<vector<int>> jobs) { // [์์ฒญ ์๊ฐ, ์์์๊ฐ]
// ๋น์ ์ sjf
int answer = 0;
vector<int> returnTime;
priority_queue<vector<int>, vector<vector<int>>, cmp> schedule;
// ์์์๊ฐ, ์์ฒญ์๊ฐ - cmp ์ ๋ ฌ ํจ์ ์ฌ์ฉ
sort(jobs.begin(), jobs.end());
int time = 0; // ํ์ฌ ์๊ฐ
int index = 0; // jobs ์ธ๋ฑ์ค
int isRunning = 0;
while(!schedule.empty() || index < jobs.size()){
// 1. ์๊ฐ์ด ๋ ๋๋ง๋ค ํ์ ์ฝ์
if(index < jobs.size() && time >= jobs[index][0]){
vector<int> v;
v.push_back(jobs[index][1]); v.push_back(jobs[index][0]);
schedule.push(v);
index++;
}
// 2. ์คํ์ค์ธ ์ํ๊ฐ ์๋ ๋, ํ top์ ๊บผ๋ด์ ์คํ
if(isRunning==0 && !schedule.empty()){
vector<int> v = schedule.top();
schedule.pop();
// ๋ฐํ์๊ฐ = ์ข
๋ฃ ์๊ฐ - ์์ฒญ ์๊ฐ
returnTime.push_back(time+v[0]-v[1]);
// cout << time+v[0]-v[1]<<"\n";
isRunning = v[0]; // ์์์๊ฐ ๋์ true์ธ ์ํ
}
time++;
if(isRunning>0) isRunning--;
}
for(int n:returnTime){
answer += n;
}
answer /= returnTime.size();
return answer;
}