코딩관계론

[프로그래머스] 카카오 셔틀버스 풀이 본문

개발/알고리즘

[프로그래머스] 카카오 셔틀버스 풀이

개발자_티모 2022. 12. 12. 00:32
반응형

아이디어 도출 방법

1. 항상 시간문제는 단위 통일하는 것이 핵심이다. 제일 작은 단위인 초로 통일하는 것을 추천합니다.

2. 초를 사용하면 시간순으로 정렬할 수 있으니 사람들이 도착하는 시간과 버스가 출발하는 시간을 비교해서 버스에 탑승 가능한 승객들을 deque에서 삭제해준다.

#탑승객과 미잠
while time_table and bus_go < n:
    """마지막 버스전까지 모든 탑승객을 태운다.
    """
    arrive_time = time_table.popleft()

    if arrive_time <= bus_start_time:
        occupant += 1
        
		#정원초과로 버스가 출발하는 경우
        if occupant == m:		
            bus_go += 1	
            occupant = 0
            bus_start_time += jump_time
    else:
        bus_go += 1
        bus_start_time += jump_time
        #이 사람은 다음 버스를 타야 하기 때문에 다시 큐에 넣어준다
        time_table.appendleft(arrive_time)

3. 남은 버스 한 대에는 주인공이 타야 함으로 정원이 차기 전 마지막 인원의 도착 시간에서 -1초 빨리 도착하면 된다. 

    while time_table:
        arrive_time = time_table.popleft()

        if arrive_time <= bus_start_time:
            if occupant + 1 == m:
                return sec_to_time(arrive_time - 1)
            occupant += 1
        else:
            break

 

from collections import deque

def time_to_sec(time):
    hour, min = map(int, time.split(':'))

    hour = hour * 3600
    min = min * 60

    return hour + min

def sec_to_time(sec):
    hour = sec // 3600
    min = (sec % 3600) // 60


    return str(hour).rjust(2,"0") + ":" + str(min).rjust(2,"0")

def solution(n, t, m, timetable):
    answer = ''

    time_table = list(map(time_to_sec, timetable))
    time_table.sort()
    time_table = deque(time_table)

    bus_start_time = time_to_sec("09:00")   #버스 시작 시간
    jump_time = t * 60

    occupant = 0
    bus_go = 1

    #항상 마지막 버스를 노린다
    while time_table and bus_go < n:
        arrive_time = time_table.popleft()

        if arrive_time <= bus_start_time:
            occupant += 1

            if occupant == m:
                bus_go += 1
                occupant = 0
                bus_start_time += jump_time
        else:
            bus_go += 1
            bus_start_time += jump_time
            time_table.appendleft(arrive_time)



    #경쟁해야 하는 인원만 남아있음 and 버스가 한대 남아 있음은 보장함
    #대기줄이 없다

    occupant = 0
    while time_table:
        arrive_time = time_table.popleft()

        if arrive_time <= bus_start_time:
            if occupant + 1 == m:
                return sec_to_time(arrive_time - 1)
            occupant += 1
        else:
            break
    
    return sec_to_time(bus_start_time)

if __name__ == "__main__":
   n=2
   t=10	
   m=2	
   time_table=["09:10", "09:09", "08:00"]
   print(solution(n, t, m, time_table))
반응형