[알고리즘] 백준 7662 - 이중 우선순위 큐

홍예주·2021년 12월 29일
0

알고리즘

목록 보기
12/92

분류 : 자료구조

1. 문제

https://www.acmicpc.net/problem/7662
이중 우선순위 큐(dual priority queue)는 전형적인 우선순위 큐처럼 데이터를 삽입, 삭제할 수 있는 자료 구조이다. 전형적인 큐와의 차이점은 데이터를 삭제할 때 연산(operation) 명령에 따라 우선순위가 가장 높은 데이터 또는 가장 낮은 데이터 중 하나를 삭제하는 점이다. 이중 우선순위 큐를 위해선 두 가지 연산이 사용되는데, 하나는 데이터를 삽입하는 연산이고 다른 하나는 데이터를 삭제하는 연산이다. 데이터를 삭제하는 연산은 또 두 가지로 구분되는데 하나는 우선순위가 가장 높은 것을 삭제하기 위한 것이고 다른 하나는 우선순위가 가장 낮은 것을 삭제하기 위한 것이다.

정수만 저장하는 이중 우선순위 큐 Q가 있다고 가정하자. Q에 저장된 각 정수의 값 자체를 우선순위라고 간주하자.

Q에 적용될 일련의 연산이 주어질 때 이를 처리한 후 최종적으로 Q에 저장된 데이터 중 최댓값과 최솟값을 출력하는 프로그램을 작성하라.

2. 입력

입력 데이터는 표준입력을 사용한다. 입력은 T개의 테스트 데이터로 구성된다. 입력의 첫 번째 줄에는 입력 데이터의 수를 나타내는 정수 T가 주어진다. 각 테스트 데이터의 첫째 줄에는 Q에 적용할 연산의 개수를 나타내는 정수 k (k ≤ 1,000,000)가 주어진다. 이어지는 k 줄 각각엔 연산을 나타내는 문자(‘D’ 또는 ‘I’)와 정수 n이 주어진다. ‘I n’은 정수 n을 Q에 삽입하는 연산을 의미한다. 동일한 정수가 삽입될 수 있음을 참고하기 바란다. ‘D 1’는 Q에서 최댓값을 삭제하는 연산을 의미하며, ‘D -1’는 Q 에서 최솟값을 삭제하는 연산을 의미한다. 최댓값(최솟값)을 삭제하는 연산에서 최댓값(최솟값)이 둘 이상인 경우, 하나만 삭제됨을 유념하기 바란다.

만약 Q가 비어있는데 적용할 연산이 ‘D’라면 이 연산은 무시해도 좋다. Q에 저장될 모든 정수는 32-비트 정수이다.

3. 풀이

시간제한이 관건이다.

1) PriorityQueue

처음에는 PriorityQueue를 이용해 최소힙과 최대힙 2가지 큐를 만들어서 문제를 풀었는데, 시간 초과에 걸렸다.
이유는 최댓값과 최솟값을 출력하면서 remove() 함수를 사용하는데, 이 때 O(n)의 시간복잡도가 발생해서 시간초과가 된다.

  1. 최소값을 삭제할 최소힙과 최대값을 삭제할 최대힙을 만든다.
  2. I 일때는 두 힙 모두에 숫자 삽입
  3. D 1 일때는 최대힙에서 최상위값 peek로 얻어와 두 힙에서 모두 삭제
  4. D -1 일때는 최소힙에서 최상위값 peek로 얻어와 두 힙에서 모두 삭제

-> 시간초과 발생(삭제 과정 때문에)

문제를 풀려면 O(log n)의 시간복잡도가 걸려야한다고 한다.
다른 사람들 풀이를 찾아보니 2가지 방법이 있다.

2) PriorityQueue + Map

원래 풀었던 방식처럼 최소힙과 최대힙을 만드는데, 새로운 숫자를 삽입할 때 두 힙에 저장해주고, 동시에 맵에 숫자에 대한 정보를 업데이트한다.
동일한 숫자가 맵에 들어오면 value값은 1씩 증가

  1. I가 들어오면 최소힙과 최대힙, 맵에 업데이트
    1) 맵에 업데이트 할 때 key는 숫자로, value는 처음에 1로 저장되도록(default는 1)
  2. D가 들어오면 최대/최소값 중 하나 삭제,
    먼저 힙에서 poll하고, 맵에서 해당 숫자의 value 확인
    1) value == 1 : 배열에 존재
    -> 맵에서 remove
    2) value == 0 : 배열에 없음
    -> 다시 다음으로 큰/작은 숫자 poll
    3) value가 0이나 1이 아님 : 배열에 존재, 여러개 있음
    -> value-1 해줌

3) TreeMap

좀 더 공부해봐야 함

4. 코드

1) Priority Queue

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

public class dualPriorityQueue {
    public static void solution() throws IOException {

        //Priority Queue로 구현
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(bf.readLine()," ");

        //테스트케이스 개수
        int tc = Integer.parseInt(st.nextToken());

        for(int i=0;i<tc;i++){

            PriorityQueue<Integer> minQueue = new PriorityQueue<>();
            PriorityQueue<Integer> maxQueue = new PriorityQueue<>(Comparator.reverseOrder());

            //연산 개수
            int k = Integer.parseInt(bf.readLine());

            for(int j=0;j<k;j++){
                st = new StringTokenizer(bf.readLine()," ");
                String op = st.nextToken();

                if(op.equals("I")){
                        int num = Integer.parseInt(st.nextToken());
                        minQueue.add(num);
                        maxQueue.add(num);
                }
                else{
                    //큐에 원소가 있을 때
                    if(!minQueue.isEmpty()){
                        int type = Integer.parseInt(st.nextToken());
                        int del_num;

                        //최대값 삭제
                        if(type==1){
                            del_num = maxQueue.peek();
                        }
                        //최솟값 삭제
                        else{
                            del_num = minQueue.peek();
                        }


                        minQueue.remove(del_num);
                        maxQueue.remove(del_num);
                    }
                }
            }

            if(!minQueue.isEmpty()){
                System.out.println(maxQueue.peek()+" "+minQueue.peek());
            }
            else{
                System.out.println("EMPTY");
            }

        }

        
    }


}

2) Priority Queue + Map

import java.io.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main {
	
	static Map<Integer, Integer> map;

	public static void main(String[] args) throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		int t = Integer.parseInt(br.readLine());
		for(int test=0; test<t; test++) {
			int input = Integer.parseInt(br.readLine());
			
			Queue<Integer> min = new PriorityQueue<>();
			Queue<Integer> max = new PriorityQueue<>(Collections.reverseOrder()); // 내림차순 
			map = new HashMap<>();
			for(int i=0; i<input; i++) {
				StringTokenizer st = new StringTokenizer(br.readLine());
				String op = st.nextToken();
				
				if(op.equals("I")) {
					int num = Integer.parseInt(st.nextToken());
					max.add(num);
					min.add(num);
					map.put(num, map.getOrDefault(num, 0)+1);
				}else {
					int type = Integer.parseInt(st.nextToken());
					
					if(map.size()==0) continue;
					if(type == 1) { //최댓값 삭제 
						delete(max);
					}else { // 최솟값 삭제
						delete(min);
					}
				}
			}
			
			if (map.size()==0) {
	            sb.append("EMPTY\n");
	        } else {
	        	int res = delete(max);
	        	sb.append(res+" "); // 최댓값 
	        	if(map.size()>0) res = delete(min);
	        	sb.append(res+"\n"); // 최솟값
	        }
		}
		System.out.println(sb.toString());
	}
	
	static int delete(Queue<Integer> q) {
		int res = 0;
		while(true) {
			res = q.poll();
			
			int cnt = map.getOrDefault(res, 0);
			if(cnt ==0) continue;
			
			if(cnt ==1) map.remove(res);
			else map.put(res, cnt-1);
			break;
		}
		
		return res;
	}
}
profile
기록용.

0개의 댓글