[백준] 11286번 절댓값 힙 (자바 풀이)

문제

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

 

11286번: 절댓값 힙

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

www.acmicpc.net

 

풀이

나는 이 문제를 Abs라는 클래스를 만들어 해결하였다. Abs 클래스는 Comparable 인터페이스를 구현하는 클래스로, 원래 자기의 값인 int num 멤버와 절댓값인 int abs를 멤버로 갖는다. 또한 compareTo 메소드를 Override하여 절댓값(abs)을 기준으로 작은 순, 절댓값이 같다면 원래 값(num)이 작은 순으로 정렬되게 한다. 이후 Abs 클래스를 우선순위 큐에 넣기만 하면 간단하게 해결된다.

 

코드

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

public class Baekjoon_11286 {
	static int N;
	public static void main(String[] args) throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		N = Integer.parseInt(br.readLine());
		PriorityQueue<Abs> pq = new PriorityQueue<>();
		for(int i=0; i<N;i++) {
			int num = Integer.parseInt(br.readLine());
			if(num == 0) {
				if(pq.isEmpty()) {
					System.out.println(0);
				}else {
					System.out.println(pq.poll().num);
				}
			}else {
				pq.add(new Abs(num));
			}
		}
	}
	
	static class Abs implements Comparable<Abs>{
		int num;
		int abs;
		Abs(int a){
			this.num  = a;
			this.abs = Math.abs(a);
		}
		
		@Override
		public int compareTo(Abs other) {
			if(this.abs == other.abs) {
				return this.num - other.num;
			}
			return this.abs - other.abs;
		}
	}

}

 

결과

반응형

댓글

Designed by JB FACTORY