본문 바로가기

문제풀기/백준 문제풀이

[알고리즘] 우선순위 큐 문제 풀이 2 (백준 11286번)

728x90
반응형

1. 절대값 힙(백준 11286번)

 

11286번: 절댓값 힙 (acmicpc.net)

 

11286번: 절댓값 힙

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

www.acmicpc.net

 

▷ 풀이 코드

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

public class absHip {
	public static void main(String args[]) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		
		int num = Integer.parseInt(br.readLine());
		
		PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new Comparator<Integer>() {
			
			@Override
			public int compare(Integer o1, Integer o2) {
				if(Math.abs(o1) < Math.abs(o2)) {
					return -1;
				} else if(Math.abs(o1) > Math.abs(o2)) {
					return 1;
				} else {
					if(o1 < o2) {
						return -1;
					} else if(o1 > o2) {
						return 1;
					} else {						
						return 0;
					}
				}
			}
			
		});
		
		
		for(int i=0; i<num; i++) {
			
			int input = Integer.parseInt(br.readLine());
			
			if(input == 0) {
				if(priorityQueue.size() <= 0) sb.append("0").append("\n");
				else {
					sb.append(priorityQueue.poll()).append("\n");
				}
			}else {priorityQueue.add(input);}
			
		}
		System.out.println(sb);
	}
}

 

이번에는 알고리즘 스터디를 통해 배운 우선순위 큐를 통해 백준 문제 풀이를 해보았습니다!!

 

우선 순위 큐를 이용했을 때 제가 원하는 방식으로 정렬 순서를 지정할 수 있네요!

 

내장되어 있는 함수들을 잘 이용하는 것이 역시나 중요하다는 것을 알 수 있네요ㅎ

 

많은 분들의 피드백은 언제나 환영합니다!  많은 댓글 부탁드려요~~

 

 

 

728x90
반응형