programming language/Structure

[프로그래머스 Level3 힙] 디스크 컨트롤러

jellylucy 2021. 8. 2. 11:39

문제

문제풀이

#include <vector>
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
struct cmp {
    bool operator()(vector<int> a, vector<int> b) {
        return a.at(1) > b.at(1);
    }
};
int solution(vector<vector<int>> jobs) {
    int answer = 0;
    priority_queue<vector<int>, vector<vector<int>>, cmp> pq; //우선순위 큐 min heap
    int size = jobs.size();
    int time=0;
    //이차원배열 정렬하기 
    sort(jobs.begin(), jobs.end());
    int idx = 0;int j=0;
    while(idx < size || !pq.empty()){
        //현재 시간보다 이하에 들어온 작업들을 모두 넣는다.
        if( idx < size && time >= jobs[idx][0] ){//&&여기 순서 틀리면 틀림..
            pq.push(jobs[idx++]);
            continue;//아래 작업하지 말고 다시 확인
            //같은 시간대에 다른 작업이 들어올수 있으므로 다시 확인한다
        }
        //현재 시간보다 아직 안 들어온 경우 idx 순서에서.
        if(!pq.empty()){
            // answer += time - pq.top()[0] + pq.top()[1];//대기 시간?
            // time += pq.top()[1];
            time += pq.top()[1];
            //작업시간에 대기 시간만큼 추가(현재시간 - 들어온 시간)
            answer += time - pq.top()[0];
            pq.pop();     
        }
        else
            time = jobs[idx][0];
    }
    return answer/size;
}