힙 - 디스크 컨트롤러(Lv.3)

jisu_log·2025년 8월 9일

알고리즘 문제풀이

목록 보기
78/105

import heapq

def solution(jobs):
    for i in range(len(jobs)):
        jobs[i].append(i)
        
    # 입력 시간 기준으로 정렬
    jobs.sort(key=lambda x:x[0])
    
    time = 0
    idx = 0
    # 대기 큐
    hp = []
    total_ret_times = 0
    
    while True:
        if idx == len(jobs) and not hp:
            break
        
        # 현재 시간보다 요청시간이 작거나 같은 경우 모두 힙에 넣어주기
        while idx < len(jobs) and jobs[idx][0] <= time:
            heapq.heappush(hp, (jobs[idx][1], jobs[idx][0], jobs[idx][2]))
            idx += 1

        # 현재 시간까지 요청된 모든 작업이 힙에 들어옴
        if hp: # 힙에 대기중인 작업이 있는 경우
            
            # 순서 주의
            length, in_time, index = heapq.heappop(hp)
            # 팝한 작업 처리하기
            time += length
            return_time = time - in_time
            # 전체 반환시간에 누적
            total_ret_times += return_time
        else: # 대기 작업이 없는 경우 1초 후로 
            time += 1
    
    
        
    return int(total_ret_times / len(jobs)) # 반환 시간의 평균

# 우선순위: 소요시간 짧은거, 요청시각 빠른거, 번호 작은거 순으로 

0개의 댓글