본문 바로가기

OJ

[BOJ] 7662 이중 우선순위 큐 (JAVA)

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

 

7662번: 이중 우선순위 큐

입력 데이터는 표준입력을 사용한다. 입력은 T개의 테스트 데이터로 구성된다. 입력의 첫 번째 줄에는 입력 데이터의 수를 나타내는 정수 T가 주어진다. 각 테스트 데이터의 첫째 줄에는 Q에 적

www.acmicpc.net

TreeMap을 이용하면 훨씬 수월하게 해결할 수 있습니다.

 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
	
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static StringBuilder sb = new StringBuilder();
    static StringTokenizer st;
    static int T, N;
    static PriorityQueue<Integer>[] pq;

    public static void main(String[] args) throws Exception {

        T = Integer.parseInt(br.readLine());
        for (int tc = 0; tc < T; tc++) {
            pq = new PriorityQueue[3];
            pq[0] = new PriorityQueue<>();
            pq[2] = new PriorityQueue<>((Comparator.reverseOrder()));
            HashMap<Integer, Integer> cnt = new HashMap<>();
            N = Integer.parseInt(br.readLine());

            for (int i = 0; i < N; i++) {
                st = new StringTokenizer(br.readLine(), " ");
                char c = st.nextToken().charAt(0);
                int val = Integer.parseInt(st.nextToken());
                if(c == 'I') {
                    pq[0].offer(val);
                    pq[2].offer(val);
                    cnt.put(val, cnt.getOrDefault(val, 0) + 1);
                } else {
                    val++;
                    while (!pq[val].isEmpty()) {
                        int poll = pq[val].poll();
                        int num = cnt.get(poll);
                        if (0 < num) {
                            cnt.put(poll, num - 1);
                            break;
                        }
                    }
                }
            }

            // 끝나고 최대 최소 출력
            int min = Integer.MAX_VALUE;
            int max = Integer.MIN_VALUE;
            boolean flag = false;
            while (!pq[0].isEmpty()) {
                int poll = pq[0].poll();
                int num = cnt.get(poll);
                if (0 < num) {
                    flag = true;
                    min = Math.min(min, poll);
                    max = Math.max(max, poll);
                }
            }
            if (!flag) sb.append("EMPTY\n");
            else sb.append(max + " " + min + "\n");
        }

        System.out.print(sb);

    }
	
}

'OJ' 카테고리의 다른 글

[BOJ] 2011 암호코드 (JAVA)  (0) 2023.04.14
[BOJ] 팩토리얼 0의 개수 (JAVA)  (0) 2023.04.13
[BOJ] 3048 개미 (JAVA)  (0) 2023.04.11
[BOJ] 2240 자두나무 (JAVA)  (0) 2023.04.10
[BOJ] 8465 스티커 (JAVA)  (2) 2023.04.09