일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- ai 전문가 과정
- Java
- 백준
- Python
- 데이터분석
- KT AIVLE
- 코딩
- 자바
- 인공지능
- github
- LG Aimers
- AIVLE
- pandas
- 코딩테스트
- 클래스
- 파이썬
- 데이터과학
- 알고리즘
- 모각코
- git
- list
- AI 윤리
- AI학습
- 정처기 실기
- numpy
- 정처기
- Ai
- KT
- dictionary
- 데이터
Archives
- Today
- Total
무향향수
[백준] 최대 힙, 최소 힙 파이썬 본문
파이썬 힙 자료구조 heapq
heapq 모듈을 사용하여 priority queue를 구현할 수 있다.
import heapq
heapq.heappush(heap, item)
# item을 heap에 추가
heapq.heappop(heap)
# heap에서 가장 작은 원소를 pop하고, 비어 있는 경우 idexError가 호출됨
heapq.heapify(x)
# 리스트 x를 heap으로 변환
최대힙
https://www.acmicpc.net/problem/11279
import sys
import heapq
N = int(sys.stdin.readline())
max_heap = []
for i in range(N):
x = int(sys.stdin.readline())
if x == 0:
if max_heap:
print(-heapq.heappop(max_heap)) # 최대힙으로 사용하기 위해 - 사용
else:
print(0)
else:
heapq.heappush(max_heap, -x) # 최대힙으로 사용하기 위해 - 사용
최소힙
https://www.acmicpc.net/problem/1927
import sys
import heapq
N = int(sys.stdin.readline())
min_heap = []
for i in range(N):
x = int(sys.stdin.readline())
if x == 0:
if min_heap:
print(heapq.heappop(min_heap))
else:
print(0)
else:
heapq.heappush(min_heap, x)
'코딩테스트' 카테고리의 다른 글
[백준] 1747번: 소수&팰린드롬 - Java, Python (2) | 2024.09.06 |
---|---|
[백준] 1920번: 수 찾기 - Java, Python (0) | 2024.09.02 |