Skip to content

Conversation

@zaqquum
Copy link
Collaborator

@zaqquum zaqquum commented Jul 6, 2025

🌱WIL

이번 한 주의 소감을 작성해주세요!

  • 이번 주는 목표 개수를 달성하지 못했다. 담 주 부터는 꼭 달성하도록 하자.

🚀주간 목표 문제 수:4 개

푼 문제


프로그래머스 #42627. 디스크컨트롤러: 구현,우선순위큐/ lv3

정리한 링크: (바로가기)

🚩플로우 (선택)

코드를 풀이할 때 적었던 플로우가 있나요?

  1. time += 1 로 wait 큐와 HD 할당을 각 시각별로 확인 및 처리

    • 반복문 종료 조건 : 모든 jobs가 HD 작업 종료
  2. wait 큐에 요청 시각에 맞춰 작업 할당하기

  3. HD 작업 진행 여부 확인(hd_timdout)

    [1] HD 작업 진행 중

    • HD 할당 시간 감소 (hd_timeout)

    [2] HD 작업 완료(hd_timeout=0) 및 비어 있을때 (hd_timeout = -1)

    (1) 진행 중인 HD 작업 완료 시

    • 완료 작업 개수 += 1 증가
    • 작업의 (종료 시점, 요청 시점) 을 정답 리스트에 반환
    • hd 비우기 (hd_timdout = -1)

    (2) Wait 큐가 jobs가 있으면 wait 큐에서 우선순위 작업 뽑아 HD에 할당하기

  4. 작업 반환 시간(turnaround_time , 요청시간 - 완료 시간) 에 대해 출력 형태 맞추기

🚩제출한 코드

import heapq
def solution(jobs):
    answer = 0 ; a = []
    wait = []
    # 반복문 종료 조건 : 모든 jobs가 HD 작업 종료
    finished = 0 ; t = 0 ; hd_timeout = -1 
    # time += 1 로 wait 큐와 HD 할당을 각 시각별로 확인 및 처리
    while finished < len(jobs) :
        # print(f"##t {t}")
        #[1] wait 큐에 요청 시각에 맞춰 작업 할당하기
        for idx , (accept_time , duration) in enumerate(jobs):
            if accept_time == t : 
                heapq.heappush(wait , [duration , accept_time, idx])

        #2. HD 작업 진행 여부 확인 
        #[1]. HD 작업 진행중 
        if hd_timeout > 0 : # HD 작업 진행중
            hd_timeout -=1 
        #[2] HD 작업 완료 및 비어 있을 때(hd_timout 음수 , 초기 시점)
        elif hd_timeout <= 0  :
            if hd_timeout == 0 : # (1) 진행중인 HD 작업 완료 -> 완료 작업 개수 += 1 
                a.append([t, start_t]) # 작업의 (종료 시점, 요청 시점) 을 정답 리스트에 반환
                finished += 1 
                hd_timeout = -1 # hd 비어있음
        
            # wait 큐의 존재하면 ->  wait큐에서 우선순위 작업을 뽑아 HD에 할당하기
            if wait : 
                hd_timeout , start_t , id = heapq.heappop(wait)
                hd_timeout = hd_timeout - 1

        t += 1

    # [4] 작업 반환 시간(turnaround_time) : 요청시간 - 완료 시간
    for e, s in a : 
        answer += (e - s) 
    answer = answer // len(a)

    return answer

💡TIL

배운 점이 있다면 입력해주세요

프로그래머스 #42628. 이중우선순위큐: 구현,우선순위큐/ lv3

정리한 링크: (바로가기)

🚩플로우 (선택)

코드를 풀이할 때 적었던 플로우가 있나요?

  1. 문제에 주어진 이중우선순위 큐 함수를 정의한다.

    1. (예외처리)빈 heap에 삭제 명령(D -1 , D 1) 이면, 무시한다.
    2. 입력 명령문 종류에 따라 3가지 동작 중 택 1을 적용한다.

    [3가지 동작]

    (1) 큐에 숫자 삽입하기 I 숫자 :

    heapq.heappush(heap , int(num))

    (2) 큐에서 최소값 삭제하기 (D -1 )

                heapq.heapify(heap)
                heapq.heappop(heap)

    (3) 큐에서 최대값 삭제하기 (D 1)

    `            heap = list(map(lambda x : -1*x , heap))
                heapq.heapify(heap)
                heapq.heappop(heap)
                heap = list(map(lambda x : -1*x , heap))
        
  2. 입력 명령문에 대해 반복문을 실행한다.

  3. 최종 큐의 상태에 따라 출력 형태를 변형한다.

    case1. 큐에 요소가 2개 이상 존재하면-> 최대값 & 최소값 출력

    case2. 큐가 비어 있으면 → [0,0

    case3. 큐에 요소가 1개만 존재하면 → [값, 값]

    • 해당 경우, 최대값= 최소값의 관계를 가진다

🚩제출한 코드

import heapq
def solution(operations):
    answer = []
    heap = []

    def prior_queue(operate , heap) : # 입력 명령문 종류에 따라 3가지 동작 중 택 1을 적용한다. 
        
        action , num = operate.split()
        # [0] (예외처리)빈 heap에 삭제 명령이면, 무시한다. 
        if not heap and action == "D": 
            return heap
        # [1] 큐에 삽입하기
        if action == "I" : 
            heapq.heappush(heap , int(num))
         # [2] 최소값 삭제
        elif action == "D" and num == "-1":
            heapq.heapify(heap)
            heapq.heappop(heap)
       #[3] 최대값 삭제
        elif action == 'D' and num == "1" :
            heap = list(map(lambda x : -1*x , heap))
            heapq.heapify(heap)
            heapq.heappop(heap)
            heap = list(map(lambda x : -1*x , heap))
    
        return heap
    
    #2. 입력 명령문에 대해 반복 동작하기
    for o in operations : 
        heap=prior_queue(o , heap )

    #3. 출력 형태 맞춰 변형하기
    if len(heap) >=2  : # (1)안 비어 있으면 -> 최대값 & 최소값 출력
        heap.sort()
        return [heap[-1] , heap[0]]
    elif len(heap) < 1 : # (2) 비어 있음 -> [0,0]
        return [0,0]
    else : # (3) heap 이 1개 남아 있을떄 -> 최대값 = 최소값 *[테케 8,9,10]
        return [heap[0] , heap[0]]
    
    return answer

💡TIL

배운 점이 있다면 입력해주세요

zaqquum added 3 commits July 6, 2025 18:43
Copy link
Collaborator

@Mingguriguri Mingguriguri left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이번 문제는 자주 풀어보지 않은 유형이기도 하고 난이도도 있어서 아마 푸는 데 쉽지 않으셨을거예요.. 그럼에도 잘 풀어주셨네요!! 너무 고생 많으셨습니다!

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

작업의 결과를 리스트에 저장하고 리스트의 길이를 answer에 나눠서 answer로 반환하는 점이 다른 코드랑 달라서 새로워서 좋네용!

Comment on lines +1 to +14
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

문제 풀이 과정을 이렇게 항상 정리해두시는데 코드 이해하는데 도움이 되는 것 같아요! 👍🏻

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment on lines +18 to +34
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 최소힙, 최대힙 2개라 나누고 동기화(number_count에 카운트)해가면서 풀이했는데 하나의 heap에 풀이하셨군요!

if cmd == 'I':
    # 삽입
    heapq.heappush(min_heap, num)
    heapq.heappush(max_heap, -num)
    number_count[num] = number_count.get(num, 0) + 1
    size += 1
else: # cmd == 'D'
    if size == 0:
        # 큐가 비어있다면 연산 무시
        continue
    
    if num == 1:
        # 최댓값 삭제
        while max_heap:
            x = -heapq.heappop(max_heap)
            if number_count.get(x, 0) > 0: 
                # num이 1번 이상 등장했다면, 카운트 반영
                number_count[x] -= 1
                size -= 1
                break
    else:
        # num == -1, 최솟값 삭제  
        while min_heap:
            x = heapq.heappop(min_heap)
            if number_count.get(x, 0) > 0: 
                # num이 1번 이상 등장했다면, 카운트 반영
                number_count[x] -= 1
                size -= 1
                break

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

함수화해서 표현한 점 좋습니당!

@zaqquum zaqquum merged commit b92e647 into main Jul 12, 2025
@github-actions
Copy link

🔥2025-07 챌린지 진행 상황

👉 그리디

  • Mingguriguri: 1개 ❌

👉 구현

  • Mingguriguri: 2개 ❌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants