코딩테스트 연습 - 주차 요금 계산

문제풀이

요금표와 주차기록이 주어졌을때, 차량번호 작은순부터 내야하는 금액을 출력하는 문제입니다. 카카오 2022 유형은 복잡한 알고리즘은 요구하지 않고 시간내에 구현하기 까다로운 문제들로 구성된듯 합니다. 풀이계획은 금방 세웠지만 작성하는데에는 30분 가량 소모됬습니다.

풀이계획

  1. 모든 차량의 주차시간 구하기.

    IN 으로 입차, OUT 으로 출차임을 알 수 있습니다. 따라서 OUT - IN 을 통해 주차한 시간을 구할 수 있습니다. 이때 시간을 분단위로 변경해서 계산해주어야 합니다.

     remain_time = dict()
        
     ...
        
     time, car, Dir = record.split()
     time_list = list(map(int, time.split(':')))
     time_to_min = time_list[0]*60 + time_list[1]
        
     ...
        
     remain_time[car] += time_to_min-(time_record[car].pop())
    

    만약 IN만 있고 OUT 이 없을 경우, 23:59에 출차한 것으로 간주합니다. 따라서 탐색이 끝난뒤 기록이 남아있다면 23:59 - IN 을 해줍니다. IN 이후 OUT이 없다면 중복으로 IN이 들어오진 않는다고 문제조건에 명시되있기 때문에, 배열내에는 단하나의 값만 존재합니다.

     for key,value in time_record.items():
     	if value:
     		if remain_time.get(key):
     			remain_time[key] += (1439-value[0])
     		else:
     			remain_time[key] = (1439-value[0])
    
  2. 각 주차시간을 금액으로 환산하기.

    기본요금 + [(기본시간 - 주차시간) / 단위시간] * 단위요금 를 이용해 내야할 금액으로 환산해줍니다. 이때 남는 시간은 올림처리 해줍니다.

    만약 기본시간보다 적게 주차했다면 기본요금만 지불합니다.

     for key,value in sorted(remain_time.items()):
     	if value > fees[0]:
     		answer.append(fees[1] + math.ceil((value-fees[0])/fees[2])*fees[3])
     	else:
     		answer.append(fees[1])
    

정답코드

import math

def solution(fees, records):
    time_record = dict()
    remain_time = dict()
    answer=[]
    
    for record in records:
        time, car, Dir = record.split()
        time_list = list(map(int, time.split(':')))
        time_to_min = time_list[0]*60 + time_list[1]
        
        if time_record.get(car):
            if Dir == 'IN':
                time_record[car].append(time_to_min)
            elif Dir == 'OUT':
                if remain_time.get(car):
                    remain_time[car] += time_to_min-(time_record[car].pop())
                else:
                    remain_time[car] = time_to_min-(time_record[car].pop())
        else:
            time_record[car] = [time_to_min]
            
    for key,value in time_record.items():
        if value:
            if remain_time.get(key):
                remain_time[key] += (1439-value[0])
            else:
                remain_time[key] = (1439-value[0])
            
    for key,value in sorted(remain_time.items()):
        if value > fees[0]:
            answer.append(fees[1] + math.ceil((value-fees[0])/fees[2])*fees[3])
        else:
            answer.append(fees[1])
    
    return answer