프로그래머스_디스크 컨트롤러_python
2021. 8. 1. 18:04ㆍ코딩테스트
반응형
https://programmers.co.kr/learn/courses/30/lessons/42627
코딩테스트 연습 - 디스크 컨트롤러
하드디스크는 한 번에 하나의 작업만 수행할 수 있습니다. 디스크 컨트롤러를 구현하는 방법은 여러 가지가 있습니다. 가장 일반적인 방법은 요청이 들어온 순서대로 처리하는 것입니다. 예를
programmers.co.kr
한번에 하나의 작업만 수행.
진행중인 작업이 없을경우 요청시간이 가장 먼저인 것 실행.
여러 작업들이 있을경우 가장 작업시간이 짧은 것으로 실행.
import heapq as hq
def solution(jobs):
j_len = len(jobs)
hq.heapify(jobs)
now, answer = hq.heappop(jobs)
now += answer
while jobs:
tmp_q = []
for tst, twt in jobs:
if tst<=now:
hq.heappush(tmp_q, [twt, tst])
if len(tmp_q) == 0:
now += 1
continue
wt2, st2 = hq.heappop(tmp_q)
jobs.remove([st2, wt2])
if now < st2:
now = st2
answer += now+wt2-st2
now += wt2
return answer//j_len
[내코드]
now, answer = hq.heappop(jobs) #현재시간에 시작시간을, answer에 작업시간을 세팅
now += answer #현재시간에 시작시간만큼 더함
시작 시간 순서대로 정렬하는 jobs을 while로 돌리면서 현재시간에 실행될 수 있는 작업을 tmp_q에 넣는다(작업시간순으로)
tmp_q중 가장 작은 것을 뽑아 다음 작업으로 할당. jobs에선 해당 데이터 삭제함.
import heapq
from collections import deque
def solution(jobs):
tasks = deque(sorted([(x[1], x[0]) for x in jobs], key=lambda x: (x[1], x[0])))
q = []
heapq.heappush(q, tasks.popleft())
current_time, total_response_time = 0, 0
while len(q) > 0:
dur, arr = heapq.heappop(q)
current_time = max(current_time + dur, arr + dur)
total_response_time += current_time - arr
while len(tasks) > 0 and tasks[0][1] <= current_time:
heapq.heappush(q, tasks.popleft())
if len(tasks) > 0 and len(q) == 0:
heapq.heappush(q, tasks.popleft())
return total_response_time // len(jobs)
[다른사람 코드]
tasks에 시작시간순서대로 (작업시간, 시작시간)으로 리스트 저장
q while돌리면서 현재 q중 첫번째 뽑음(작업시간이 젤 짧은거)
남은 task중에 시작시간이 현재시간 이하인 것들 q에 넣음.
남은 task가 있으면서, q에 있는 데이터가 없을 경우 q에 다 넣..
반응형
'코딩테스트' 카테고리의 다른 글
프로그래머스_K번째 수_python (0) | 2021.08.04 |
---|---|
프로그래머스_이중우선순위큐_python (0) | 2021.08.04 |
프로그래머스_더 맵게_python (0) | 2021.07.29 |
프로그래머스_다리를 지나는 트럭_python (0) | 2021.07.29 |
프로그래머스_주식가격_python (0) | 2021.07.27 |