20250806 baekjoon

This commit is contained in:
songyc macbook 2025-08-06 21:47:43 +09:00
parent da63f73953
commit cbf08beae3
2 changed files with 95 additions and 0 deletions

View File

@ -0,0 +1,73 @@
#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b);
void insert(int value, int *heap, int* size);
void delete(int *heap, int* size);
int main(){
int N;
scanf("%d",&N);
int *heap = (int*)malloc(sizeof(int)*(N+1));
int heap_size = 0;
while(N--){
int op;
scanf("%d",&op);
if(op==0) delete(heap, &heap_size);
else insert(op, heap, &heap_size);
}
free(heap);
return 0;
}
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}
void insert(int value, int *heap, int* size){
heap[++(*size)] = value;
int current = *size;
while(current != 1){
if((abs(heap[current]) < abs(heap[current/2]) ||
(abs(heap[current]) == abs(heap[current/2]) && heap[current]<heap[current/2]))){
swap(&heap[current], &heap[current/2]);
current /= 2;
}
else {
break;
}
}
}
void delete(int *heap, int* size){
if(*size==0){
printf("0\n");
return;
}
printf("%d\n",heap[1]);
heap[1] = heap[(*size)--];
int current = 1;
while (current * 2 <= *size) {
int child = current * 2;
if (child + 1 <= *size &&
((abs(heap[child + 1]) < abs(heap[child])) ||
(abs(heap[child + 1]) == abs(heap[child]) && heap[child + 1] < heap[child]))) {
child++;
}
if ((abs(heap[child]) < abs(heap[current])) ||
(abs(heap[child]) == abs(heap[current]) && heap[child] < heap[current])) {
swap(&heap[current], &heap[child]);
current = child;
}
else {
break;
}
}
}

View File

@ -0,0 +1,22 @@
import java.util.*;
public class _11286{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PriorityQueue<Integer> absHeap = new PriorityQueue<>((a,b) -> {
if(Math.abs(a) == Math.abs(b)) {
return a - b;
}
return Math.abs(a) - Math.abs(b);
});
int N = sc.nextInt();
for(int i = 0; i<N; i++){
int op = sc.nextInt();
if(op==0) System.out.println(absHeap.isEmpty() ? 0 : absHeap.poll());
else absHeap.add(op);
}
sc.close();
}
}