https://www.acmicpc.net/problem/7662
정답률 22.007%
이중 우선순위 큐(dual priority queue)는 전형적인 우선순위 큐처럼 데이터를 삽입, 삭제할 수 있는 자료 구조이다. 전형적인 큐와의 차이점은 데이터를 삭제할 때 연산(operation) 명령에 따라 우선순위가 가장 높은 데이터 또는 가장 낮은 데이터 중 하나를 삭제하는 점이다. 이중 우선순위 큐를 위해선 두 가지 연산이 사용되는데, 하나는 데이터를 삽입하는 연산이고 다른 하나는 데이터를 삭제하는 연산이다. 데이터를 삭제하는 연산은 또 두 가지로 구분되는데 하나는 우선순위가 가장 높은 것을 삭제하기 위한 것이고 다른 하나는 우선순위가 가장 낮은 것을 삭제하기 위한 것이다.
정수만 저장하는 이중 우선순위 큐 Q가 있다고 가정하자. Q에 저장된 각 정수의 값 자체를 우선순위라고 간주하자.
Q에 적용될 일련의 연산이 주어질 때 이를 처리한 후 최종적으로 Q에 저장된 데이터 중 최댓값과 최솟값을 출력하는 프로그램을 작성하라.
2
7
I 16
I -5643
D -1
D 1
D 1
I 123
D -1
9
I -45
I 653
D 1
I -642
I 45
I 97
D 1
D -1
I 333
EMPTY
333 -45
이 문제는 2가지 방법으로 풀 수 있다.
먼저 최대 힙과 최소 힙으로 풀이한다.
2개의 우선순위 큐를 만들어, 최대 힙과 최소 힙을 구현한다. 이때 각 큐는 동기화되어야 하는데 매 연산마다 큐를 동기화시키면(큐를 비우고, 다시 삽입하는 과정) 연산의 최댓값은 1,000,000이므로 시간초과가 발생한다. 따라서 값의 개수를 저장할 HashMap 또한 생성한다.
Queue<Integer> min = new PriorityQueue<>();
Queue<Integer> max = new PriorityQueue<>(Comparator.comparingInt(Integer::intValue).reversed());
Map<Integer, Integer> map = new HashMap<>();
그다음 문제의 요구사항대로 I일 때는 값을 저장하고, D일 때는 값을 삭제한다.
String[] split = br.readLine().split(" ");
String str = split[0];
int n = Integer.parseInt(split[1]);
if (str.equals("I")) {
//map에 n의 개수 저장
map.put(n, map.getOrDefault(n, 0) + 1);
min.add(n);
max.add(n);
} else if (str.equals("D") && !map.isEmpty()) {
//D 1일 경우 최대힙에서 제거
if (n == 1) {
removeMap(max, map);
}
//D -1일 경우 최소힙에서 제거
else {
removeMap(min, map);
}
}
힙에서 데이터를 삭제하는 메서드는 다음과 같이 구성한다. 이때 count가 0일 때는 생략하는데 최대 힙과 최소 힙은 실시간으로 데이터가 동기화되지 않는다. 만약 최대 힙에서 특정 값을 제거하여 map에서 삭제되었어도 최소 힙에는 값이 남아있다. 그런데 최소 힙에서 해당 메서드를 호출하면 count는 0이 되고 이미 삭제된 값이기 때문에 다음 과정을 생략하고 다음 우선순위의 값을 가져온다.
private static Integer removeMap(Queue<Integer> queue, Map<Integer, Integer> map) {
while (true) {
Integer n = queue.poll();
Integer count = map.getOrDefault(n, 0);
//다른 queue에서 이미 삭제되어 count가 0일 경우
if (count == 0) {
continue;
}
//count가 1이면 map에서 삭제
if (count == 1) {
map.remove(n);
}
//1보다 크면 poll의 값만 -1
else {
map.put(n, count - 1);
}
return n;
}
}
연산을 다 진행하고 map이 비어있으면 EMPTY를 출력하고, 존재하면 최댓값과 최솟값을 출력한다.
if (map.isEmpty()) {
System.out.println("EMPTY");
} else {
Integer maxValue = removeMap(max, map);
Integer minValue;
if (map.isEmpty()) {
minValue = maxValue;
} else {
minValue = removeMap(min, map);
}
System.out.println(maxValue + " " + minValue);
}
//백준
public class Main {
public static void main(String[] args) throws IOException {
System.setIn(new FileInputStream("src/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
for (int testCase = 0; testCase < T; testCase++) {
int Q = Integer.parseInt(br.readLine());
Queue<Integer> min = new PriorityQueue<>();
Queue<Integer> max = new PriorityQueue<>(comparingInt(Integer::intValue).reversed());
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < Q; i++) {
String[] split = br.readLine().split(" ");
String str = split[0];
int n = Integer.parseInt(split[1]);
if (str.equals("I")) {
//map에 n의 개수 저장
map.put(n, map.getOrDefault(n, 0) + 1);
min.add(n);
max.add(n);
} else if (str.equals("D") && !map.isEmpty()) {
//D 1일 경우 최대힙에서 제거
if (n == 1) {
removeMap(max, map);
}
//D -1일 경우 최소힙에서 제거
else {
removeMap(min, map);
}
}
}
if (map.isEmpty()) {
System.out.println("EMPTY");
} else {
Integer maxValue = removeMap(max, map);
Integer minValue;
if (map.isEmpty()) {
minValue = maxValue;
} else {
minValue = removeMap(min, map);
}
System.out.println(maxValue + " " + minValue);
}
}
}
private static Integer removeMap(Queue<Integer> queue, Map<Integer, Integer> map) {
while (true) {
Integer n = queue.poll();
Integer count = map.getOrDefault(n, 0);
//다른 queue에서 이미 삭제되어 count가 0일 경우
if (count == 0) {
continue;
}
//count가 1이면 map에서 삭제
if (count == 1) {
map.remove(n);
}
//1보다 크면 poll의 값만 -1
else {
map.put(n, count - 1);
}
return n;
}
}
}
PriorityQueue 두 개를 동시에 사용하여 값을 동기화하려는 시도는 비효율적이므로, TreeMap 같은 자료 구조를 사용하면 최소값과 최대값을 효율적으로 관리할 수 있다.
TreeMap은 이진 탐색 트리의 일종인 레드-블랙 트리(Red-Black Tree)로 구현되어 있어, 항목들이 자동으로 키를 기준으로 정렬된다. 이로 인해 삽입, 삭제, 탐색 연산의 평균 시간 복잡도가 으로 효율적이다.
우선 TreeMap을 다음과 같이 생성한다.
TreeMap<Integer, Integer> map = new TreeMap<>();
나머지는 최대/최소 힙과 동일하나 최댓값과 최솟값을 제거하는 부분을 다음과 같이 구성한다.
if (str.equals("I")) {
map.put(n, map.getOrDefault(n, 0) + 1);
} else if (str.equals("D") && !map.isEmpty()) {
//D 1일 경우 최댓값 제거
if (n == 1) {
int maxKey = map.lastKey();
if (map.get(maxKey) == 1) {
map.remove(maxKey);
} else {
map.put(maxKey, map.get(maxKey) - 1);
}
}
//D -1일 경우 최솟값 제거
else if (n == -1) {
int minKey = map.firstKey();
if (map.get(minKey) == 1) {
map.remove(minKey);
} else {
map.put(minKey, map.get(minKey) - 1);
}
}
}
그리고 연산을 다 진행하였으면 간단히 최댓값과 최솟값을 불러와 출력하면 된다.
if (map.isEmpty()) {
System.out.println("EMPTY");
} else {
System.out.println(map.lastKey() + " " + map.firstKey());
}
//백준
public class Main {
public static void main(String[] args) throws IOException {
System.setIn(new FileInputStream("src/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
for (int testCase = 0; testCase < T; testCase++) {
int Q = Integer.parseInt(br.readLine());
TreeMap<Integer, Integer> map = new TreeMap<>();
for (int i = 0; i < Q; i++) {
String[] split = br.readLine().split(" ");
String str = split[0];
int n = Integer.parseInt(split[1]);
if (str.equals("I")) {
map.put(n, map.getOrDefault(n, 0) + 1);
} else if (str.equals("D") && !map.isEmpty()) {
//D 1일 경우 최댓값 제거
if (n == 1) {
int maxKey = map.lastKey();
if (map.get(maxKey) == 1) {
map.remove(maxKey);
} else {
map.put(maxKey, map.get(maxKey) - 1);
}
}
//D -1일 경우 최솟값 제거
else if (n == -1) {
int minKey = map.firstKey();
if (map.get(minKey) == 1) {
map.remove(minKey);
} else {
map.put(minKey, map.get(minKey) - 1);
}
}
}
}
if (map.isEmpty()) {
System.out.println("EMPTY");
} else {
System.out.println(map.lastKey() + " " + map.firstKey());
}
}
}
}