본문 바로가기
PS(Problem Solving)/백준_BOJ

[백준] 1927번 - 최소 힙 (C++/파이썬) 문제 및 풀이

by 초코칩프라푸치노 2021. 4. 14.

문제) 백준 - 우선수위 큐 (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++ 소스 코드)

#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;
}
view raw 1927.cpp hosted with ❤ by GitHub

파이썬 소스 코드)

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)
view raw 1927.py hosted with ❤ by GitHub

 

 

반응형

댓글