[백준]11286번 절댓값 힙

김윤지·2022년 10월 4일
0

JAVA

목록 보기
8/10

문제 해석

풀이 방법
compare를 통해 절대값 기준 비교하기
=>절대값 기준으로 앞 값이 더 클 경우 자리를 바꿔주기
=> 절대값 기준으로 두 값이 같다면 음수를 앞으로 보내주기
for문으로 N만큼 반복하면서
=>if: 요청이 0일 경우 큐가 비어있을 때, 비어있지 않을 때를 비교하기 =>else: 요청이 1일 경우 새로운 데이터를 우선순위 큐에 더하기

내 코드 1

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.PriorityQueue;

public class Main {
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int N = Integer.parseInt(br.readLine());
		
		// compare 비교를 통해 절댓값 비교!
		PriorityQueue<Integer> pq = new PriorityQueue<Integer>(new Comparator<Integer>() {
			@Override
			public int compare(Integer o1, Integer o2) {
				//절대값 기준으로 앞 값이 더 크다면 자리를 바꿔준다.
				if(Math.abs(o1) > Math.abs(o2)) {
					return Math.abs(o1) - Math.abs(o2);
				//절대값 기준으로 두 값이 같다면 음수를 앞으로 보내준다.
				}else if(Math.abs(o1) == Math.abs(o2)) {
					return o1 - o2;
				}else {
					return -1;
				}
			}
		});
		
		for(int i = 0; i < N; i++) {
			int x = Integer.parseInt(br.readLine());
			if(x == 0) { 
				if(pq.isEmpty()) {
					System.out.println("0");;
				} else {
					System.out.println(pq.remove());;
				}
			}else {
				pq.add(x);
			}
		}
		br.close();
	}
}

System.out.println()으로 결과를 출력하면 입력할 때 마다 결과를 반환하는 오류 발생함!

그래서 어떻게 해야할까 고민하다가 검색해보니까 StringBuilder 를 사용하는 것을 찾아서 적용해봄(사용하는 이유 참고)

제출한 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;
import java.util.PriorityQueue;

public class Main {
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int N = Integer.parseInt(br.readLine());
		
		// compare 비교를 통해 절댓값 비교!
		PriorityQueue<Integer> pq = new PriorityQueue<Integer>(new Comparator<Integer>() {
			@Override
			public int compare(Integer o1, Integer o2) {
				//절대값 기준으로 앞 값이 더 크다면 자리를 바꿔준다.
				if(Math.abs(o1) > Math.abs(o2)) {
					return Math.abs(o1) - Math.abs(o2);
				//절대값 기준으로 두 값이 같다면 음수를 앞으로 보내준다.
				}else if(Math.abs(o1) == Math.abs(o2)) {
					return o1 - o2;
				}else {
					return -1;
				}
			}
		});
		
		StringBuilder sb = new StringBuilder();
		
		for(int i = 0; i < N; i++) {
			int x = Integer.parseInt(br.readLine());
			if(x == 0) {
				if(pq.isEmpty()) {
					sb.append("0").append("\n");
				} else {
					sb.append(pq.remove()).append("\n");
				}
			}else {
				pq.add(x);
			}
		}
		System.out.println(sb);
		br.close();
	}
}

통과~~

profile
Java, Javascript, python, DB

0개의 댓글