-
11279 - 최대 힙알고리즘 2023. 5. 30. 19:35728x90
https://www.acmicpc.net/problem/11279
11279번: 최대 힙
첫째 줄에 연산의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 N개의 줄에는 연산에 대한 정보를 나타내는 정수 x가 주어진다. 만약 x가 자연수라면 배열에 x라는 값을 넣는(추가하는) 연산이고, x가 0
www.acmicpc.net
문제요약
- 가장 큰수를 계속해서 지우거나, 비어있을 경우 0을 출력하는 문제
내가 가지고 있는 데이터가 계속해서 정렬시켜야하는 문제이다.
그리고 제거도 해야하므로, PriorityQueue를 역순으로 적용하는 작업을 했다.import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Collections; import java.util.PriorityQueue; public class Main { public static void main(String[] args) throws IOException { PriorityQueue<Integer> reversePq = new PriorityQueue<>(Collections.reverseOrder()); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int rows = Integer.parseInt(br.readLine()); for (int i = 0; i < rows; i++) { int input = Integer.parseInt(br.readLine()); if(input == 0){ if(reversePq.isEmpty()) sb.append(input + "\n"); else sb.append(reversePq.poll()+"\n"); } else reversePq.add(input); } System.out.println(sb); } }
느낀점
내가 선택한 자료구조 외에도 다양한 방법이 존재할 수 있지만, 문제를 해결하기에 가장 적합한
자료구조를 선택하는 작업이 매우 중요한 문제였다.
'알고리즘' 카테고리의 다른 글
2798 - 블랙잭 (0) 2023.05.30 11866 - 요세푸스 문제 0 (0) 2023.05.30 4949 - 균형잡힌 세상 (0) 2023.05.30 9012 - 괄호 (0) 2023.05.26 1021 - 회전하는 큐 (0) 2023.05.26