https://www.acmicpc.net/problem/1927

 

1927번: 최소 힙

첫째 줄에 연산의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0

www.acmicpc.net

코드설명

우선순위큐를 활용하여 최소힙을 구하는 문제입니다.

 

단순히, 우선순위큐를 사용할 줄 안다면 쉽게 해결할 수 있습니다.

 

코드

코드1입니다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static int N, K;
public static String[] arr;
public static PriorityQueue<Node> pq = new PriorityQueue<Node>();
public static int answer = 0;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
for(int i=0;i<N;i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
if( a == 0 && pq.size() == 0) {
System.out.println("0");
} else if( a == 0 && pq.size() > 0) {
System.out.println(pq.poll().value);
} else if( a > 0) {
pq.offer(new Node(a));
}
}
}
}

 

코드 2입니다.

package Main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main {
public static int C, N, M;
public static int answer = 0;
public static PriorityQueue<Integer> pq = new PriorityQueue<>();
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
for(int i=0;i<N; i++) {
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
if(x > 0) {
pq.add(x);
}
if(x == 0) {
if(pq.isEmpty()) System.out.println(0);
else System.out.println(pq.poll());
}
}
}
}

+ Recent posts