문제) 백준 - 우선수위 큐 (Priority Queue) - 최소 힙
-> www.acmicpc.net/problem/1927
1181번: 단어 정렬
첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.
www.acmicpc.net
C++은 최소 힙 구현을 위해서 다음과 같이 선언한다. 기본은 최대 힙. 파이썬과 반대이므로 헷갈리지 않도록 유의하자.
priority_queue<int, vector<int>, greater<int>> heap;
C++ 소스 코드)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
#define endl "\n" | |
using namespace std; | |
int main() { | |
ios::sync_with_stdio(false); | |
cout.tie(0); cin.tie(0); | |
//Min Heap | |
priority_queue<int, vector<int>, greater<int>> heap; | |
int n; cin >> n; | |
for (int i = 0; i < n; ++i) { | |
int temp; cin >> temp; | |
if (temp != 0) heap.push(temp); | |
else { | |
if (heap.empty()) cout << 0 << endl; | |
else { | |
cout << heap.top() << endl; | |
heap.pop(); | |
} | |
} | |
} | |
return 0; | |
} |
파이썬 소스 코드)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import heapq | |
import sys | |
input = sys.stdin.readline | |
q = [] | |
n = int(input()) | |
for _ in range(n): | |
temp = int(input()) | |
if temp == 0: | |
if q: | |
print(heapq.heappop(q)) | |
else: | |
print(0) | |
else: | |
heapq.heappush(q, temp) |
반응형
'PS(Problem Solving) > 백준_BOJ' 카테고리의 다른 글
[백준] 1715번 - 카드 정렬하기 (C++/파이썬) 문제 및 풀이 (0) | 2021.04.14 |
---|---|
[백준] 11279번 - 최대 힙 (C++/파이썬) 문제 및 풀이 (0) | 2021.04.14 |
[백준] 1181번 - 단어 정렬 (C++/파이썬) 문제 및 풀이 (0) | 2021.04.14 |
[백준] 1991번 - 트리 순회 (C++/파이썬) (0) | 2021.04.14 |
[백준] 2437번 - 저울 (C++/파이썬) (0) | 2021.04.13 |
댓글