본문 바로가기
Problem Solving/Baekjoon

[백준] 11279 최대 힙 - Data Structure / Java

by graycode 2022. 7. 24.

 문제 링크

 

11279번: 최대 힙

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

www.acmicpc.net

 

 풀이 과정

 

[백준] 1927 최소 힙 - Data Structure / Java

• 문제 링크 1927번: 최소 힙 첫째 줄에 연산의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을

graycode.tistory.com

위 문제와 전체적인 구조는 유사하나 해당 문제에선 최소값 대신 최대값을 우선 순위로 둔다.

 

PriorityQueue 자료구조의 매개변수에 (o1, o2) -> o2 - o1 와 같이 람다식,

또는 Comparator.reverseOrder() 를 전달하여 우선 순위를 내림차순으로 지정한다.

 

변경된 우선 순위와 x 값과 큐의 원소 유무에 대한 조건문에 의해 정답을 구한다.

 

 풀이 코드

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.PriorityQueue;

public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

		int n = Integer.parseInt(br.readLine());

		PriorityQueue<Integer> q = new PriorityQueue<>((o1, o2) -> o2 - o1);
		for (int i = 0; i < n; i++) {
			int x = Integer.parseInt(br.readLine());

			if (x == 0)
				if (q.isEmpty())
					bw.write(0 + "\n");
				else
					bw.write(q.poll() + "\n");
			else
				q.offer(x);
		}

		bw.flush();
	}

}

댓글