미소를뿌리는감자의 코딩
[백준 2024/02/21] 5939번 Race Results 본문
728x90
https://www.acmicpc.net/problem/5939
1. 접근 방법
문제 파악이 단순했던 문제이다. 그냥 race 기록을 가지고, 빠른 순서로 출력하면 되는 문제이다.
빠른 순으로 출력을 보니, heap이 생각이 났고, minheap을 이용하여 출력하고자 길을 잡았다.
heapq.heappush(heap, element)
의 작동방식을 이용하여 넣어주었다.
이후 print_time이라는 함수에서, heap이 비어질 때까지 heappop을 해주었다.
IF 비교 순서가 시 분 초 가 아닌, 분 -> 시 -> 초 와 같다면 어떻게 될까?
그럴 땐 tuple을 사용하는 것이 좋다.
Tuple을 이용하여 처음엔 비교 값, 두 번째는 보존할 값을 넣어주는 것이다.
heapq.heappush(heap, (compare_time(time), time))
이런식으로 값을 넣는 이유는, 튜플의 첫 번째 요소 : compare_time(time)을 통해서, 정렬 기준을 삼고,
튜플의 두 번쨰 요소 : time을 통해서 본래의 값을 보존하기 위함이다.
def compare_time(time):
return (time[0], time[1], time[2])
compare_time에서의 반환은 다음과 같다. 만약 분 -> 시 -> 초 로 오름차순 정렬을 하고 싶다면,
time[1] -> time[0] -> time[2]로 값을 적는다.
그렇다면 tuple을 왜 사용한 것일까?
1. 자동 정렬 기능: python의 튜플은 비교 시 첫 번째 요소부터 순차적으로 비교를 수행.
2. 복합 데이터 관리: 여러 종류의 데이터를 하나의 요소로 그룹화 할 수 있음.
3. 변경 불가능: tuple의 immutable 특성
2. 코드
import heapq
def input_time():
time = list(map(int, input().split()))
heapq.heappush(heap, time)
def print_time():
time = heapq.heappop(heap)
print(time[0], time[1], time[2])
if __name__ == '__main__':
heap = []
for i in range(int(input())):
input_time()
while heap:
print_time()
--- 분 -> 시 -> 초 로 값을 변경할 수 있는 코드 ---
import heapq
def compare_time(time):
return (time[0], time[1], time[2])
def input_time():
time = list(map(int, input().split()))
heapq.heappush(heap, (compare_time(time), time))
def print_time():
time = heapq.heappop(heap)
print(time[1][0], time[1][1], time[1][2])
if __name__ == '__main__':
heap = []
for i in range(int(input())):
input_time()
while heap:
print_time()
728x90
'코딩 테스트 > 백준' 카테고리의 다른 글
[백준 2024/02/21] 1011번 Fly me to the Alpha Centauri - python ver. (1) | 2024.02.21 |
---|---|
[백준 2024/02/21] 14534번 String Permutation (0) | 2024.02.21 |
[백준 2024/02/20] 17779번 게리맨더링 2 (1) | 2024.02.20 |
[백준 2024/02/20] 11559번 Puyo Puyo (0) | 2024.02.20 |
[백준 2024/02/20] 20055번 컨베이어 벨트 위의 로봇 (0) | 2024.02.20 |