본문 바로가기
Algorithm/📖Baekjoon

#1927 최소 힙

by yewoneeee 2022. 4. 27.

# 문제

# 입력 및 출력

# 풀이

우선순위 큐를 사용해서 최소 힙, 최대 힙 구현 방법은 아래 블로그 참고

https://breakcoding.tistory.com/123

 

[C++] <queue> 라이브러리, 우선순위 큐, 최대 힙, 최소 힙

C++에서 우선순위 큐를 구현하려면 라이브러리를 사용하면 된다. 따라서 #include 코드를 써줘야 한다. priority_queue - C++ Reference container_typeThe second template parameter (Container)Type of the und..

breakcoding.tistory.com

우선순위 큐를 선언하면 디폴트가 최대 힙임 [priority_queue<int, vector<int>> q; ]

최소 힙으로 선언하고 싶다면 [ priority_queue<int, vector<int>, greater<int>> q; ] 세 번째 인자 넣어주기

이 문제도 cin, cout, endl을 사용했다가 시간초과가 나서 scanf, printf, \n으로 변경해줌

 

#pragma warning(disable:4996)
#include <iostream>
#include <queue>
using namespace std;

int main() {
	int n, inp;
	scanf("%d", &n);
	priority_queue<int, vector<int>, greater<int>> q;
	for (int i = 0; i < n; i++) {
		scanf("%d", &inp);
		if (inp == 0) {
			if (q.empty()) printf("0\n");
			else {
				printf("%d\n", q.top());
				q.pop();
			}
		}
		else q.push(inp);
	}
}

 

'Algorithm > 📖Baekjoon' 카테고리의 다른 글

#10610 30  (0) 2022.04.28
#11279 최대 힙  (0) 2022.04.27
#1874 스택 수열  (0) 2022.04.27
#2164 카드2  (0) 2022.04.26
#10773 제로  (0) 2022.04.25

댓글