title: "[프로그래머스] 디스크 컨트롤러 Python 파이썬 해설 (Level 3) - 이도훈"
cleanUrl: "programmers/42627"
description: "프로그래머스 Level 3 문제 [디스크 컨트롤러]의 풀이를 정리합니다."

문제 설명 및 제한사항

아이디어 및 해결 방법

코드

from queue import PriorityQueue

def solution(jobs):
    # 작업 중이 아닐 때 : 가장 빠른 job을 수행한다.
    # 작업 중일 때 : 요청이 들어오면 duration이 작은 순서대로 꺼낼 수 있도록 queue에 넣어둔다.
    # 작업 중인지 판단은 queue가 비었는지 아닌지로 판단.
    n = len(jobs)
    
    jobs = [(d, t) for t, d in jobs]
    jobs.sort(key=lambda x: (x[1], x[0]))
    
    answer = 0
    q = PriorityQueue()
    job_idx, t = 0, 0
    n_processed = 0
    while n_processed != n:
        # 작업 중이 아님. 가장 빠른 job을 수행한다.
        if q.empty():
            duration, t_req = jobs[job_idx]
            t = t_req  # 요청이 들어오는 시점으로 현재 시점을 이동한다.
            answer += duration
            n_processed += 1
            
            # 작업 기간 내에 요청이 들어온 job은 queue에 넣어준다.
            job_idx += 1
            while job_idx < n and (t <= jobs[job_idx][1] <= t + duration):
                q.put(jobs[job_idx])
                job_idx += 1
            # job_idx는 이제 작업 기간 이후에 들어오는 작업을 가리키고 있다.
            t += duration
        else:
            duration, t_req = q.get()
            answer += (t + duration) - t_req
            n_processed += 1
            
            # 작업 기간 내에 요청이 들어온 job은 queue에 넣어준다.
            while job_idx < n and t <= jobs[job_idx][1] <= t + duration:
                q.put(jobs[job_idx])
                job_idx += 1
                
            t += duration
            
    return int(answer / n)

출처

프로그래머스 코딩테스트 연습 https://school.programmers.co.kr/learn/challenges