중요 지식
힙 - 빠르게 최소값을 찾기 위함
코드
#include <iostream>
using namespace std;
typedef struct heap{
int arr[100001];
int size;
} heap;
void initHeap(heap *hp){
hp->size = 0;
}
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}
void insert(heap *hp, int data){
int here = ++hp->size;
while(here!=1 && data < hp->arr[here/2]){
hp->arr[here] = hp->arr[here/2];
here /= 2;
}
hp->arr[here] = data;
}
int deleteData(heap *hp) {
if (hp->size == 0) return 0;
int ret = hp->arr[1];
hp->arr[1]=hp->arr[hp->size--];
int parent = 1;
int child;
while (1) {
child = parent * 2;
if (child + 1 <= hp->size && hp->arr[child]>hp->arr[child + 1])
child++;
if (child>hp->size||hp->arr[child] > hp->arr[parent]) break;
swap(&hp->arr[parent], &hp->arr[child]);
parent = child;
}
return ret;
}
int main(){
int N;
heap *hp = new heap;
cin >> N;
initHeap(hp);
for(int i = 0; i < N; i++){
int x;
scanf("%d", &x);
if(x == 0){
printf("%d\n", deleteData(hp));
}else{
insert(hp, x);
}
}
return 0;
}
풀이
힙을 활용해서 풀면 된다
'프로그래밍 문제집 > 백준' 카테고리의 다른 글
1676번-팩토리얼 (미완성) (0) | 2022.02.14 |
---|---|
7662번-이중 우선순위 큐 (0) | 2022.02.12 |
1541번-잃어버린 괄호 (0) | 2022.02.09 |
1389번: 케빈 베이컨의 6단계 법칙 (0) | 2022.02.09 |
1107번-리모컨 (0) | 2022.02.07 |