알고리즘
백준 1927번 최소 힙 (JAVA)
박카스마시며코딩
2022. 1. 1. 23:02
https://www.acmicpc.net/problem/1927
1927번: 최소 힙
첫째 줄에 연산의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0
www.acmicpc.net
저는 우선 순위 큐를 통해 해당 문제를 해결하였습니다. 처음에 우선순위 큐가 비어있는지를 확인하지 않아 틀렸었습니다.
package BOJ;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.function.Function;
public class BOJ_1927 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine()," ");
PriorityQueue<Integer> pq = new PriorityQueue<>();
Function<String,Integer> stoi = Integer::parseInt;
int n = stoi.apply(st.nextToken());
for(int i = 0 ; i < n ; i++){
st = new StringTokenizer(br.readLine()," ");
int num = stoi.apply(st.nextToken());
if(num != 0){
pq.offer(num);
}else{
if(pq.isEmpty()){
System.out.println(0);
}else{
System.out.println(pq.poll());
}
}
}
}
}