자바로 백준 11286 풀기

hong030·2023년 7월 7일
0
  • 실버 1단계 문제

풀이)

숫자는 최대 10만개가 주어지며, 데이터가 삽입될 때마다 절댓값에 기인해 정렬을 해줘야 하므로 우선순위 큐로 문제를 풀자.
우선순위는 절댓값이 가장 작은 애들이 먼저, 그리고 절댓값이 같으면 음수인 수가 먼저 와야 한다.

우선순위 큐의 우선순위를 직접 커스텀 하는 방법.
우선 순위가 높은 게 - 값을 갖게 해야 함.

//일반 우선순위큐
PriorityQueue<Integer> queue = new PriorityQueue<>();

//커스터마이징
PriorityQueue<Integer> queue = new PriorityQueue<>(
	(a, b)->{
		int A = Math.abs(a);
		int B = Math.abs(b);
		//절대값이 같은 수 중 작은 애가 음수를 가짐.
		if(A == B) {
			return a>b? 1:-1;
		}
		//만약 A가 B보다 작으면 리턴이 음수이므로 A가 우선순위를 가짐. 
		return A - B;
});

내 코드)

// 백준 온라인 저지 11286번

import java.io.*;
import java.util.*;

public class Main{
	public static void main(String[]args) throws IOException{

		// 입력
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		int N = Integer.parseInt(bf.readLine());

		// 우선순위 큐 만들기.
		PriorityQueue<Integer> queue = new PriorityQueue<>(
				(a, b)->{
					int A = Math.abs(a);
					int B = Math.abs(b);
					//절대값이 같은 수 중 작은 애가 음수를 가짐.
					if(A == B) {
						return a>b? 1:-1;
					}
					//만약 A가 B보다 작으면 리턴이 음수이므로 A가 우선순위를 가짐.  
					return A - B;
				});
		
		// 입력받고 출력하기.
		for(int i=0;i<N;i++) {
			int input = Integer.parseInt(bf.readLine());
			if (input==0) {
				if(queue.size()==0)
					System.out.println(0);
				else
					System.out.println(queue.remove());			
			}else {
				queue.add(input);
			}
		}
		
	}
}
profile
자바 주력, 프론트 공부 중인 초보 개발자. / https://github.com/hongjaewonP

0개의 댓글