package org.example;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(reader.readLine());
StringBuilder sb = new StringBuilder();
//1사이클
// 문서 갯수, 출력해야 하는 문서
// 문서들이 있다.
for(int i = 0; i < N; i++){
String[] doc = reader.readLine().split(" ");
int printDocIndex = Integer.parseInt(doc[1]);
String[] priorities = reader.readLine().split(" ");
Queue<Document> queue = new LinkedList<>();
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Collections.reverseOrder());
for(int j = 0; j<priorities.length; j++){
int priority = Integer.parseInt(priorities[j]);
//큐에 담는다.
queue.add(new Document(j, priority));
priorityQueue.add(priority);
}
int count = 0;
while(!queue.isEmpty()){
Document current = queue.poll();
if (current.priority == priorityQueue.peek()) {
priorityQueue.poll();
count++;
if (current.index == printDocIndex) {
sb.append(count).append("\n");
break;
}
} else {
queue.add(current);
}
}
}
System.out.println(sb.toString());
}
}
class Document{
final int index;
final int priority;
Document(int index, int priority) {
this.index = index;
this.priority = priority;
}
}
1
9 0
1 1 9 1 1 9 6 7 8
# 결과 : 8
# 정답 : 6
Queue<Document> queue = new LinkedList<>();
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Collections.reverseOrder());
우선순위 큐와 일반 큐를 2개 준비한다.
for(int j = 0; j<priorities.length; j++){
int priority = Integer.parseInt(priorities[j]);
queue.add(new Document(j, priority));
priorityQueue.add(priority);
}
각각 일반 큐에는 우선순위와 인덱스 값을, 우선순위 큐에는 우선순위 값을 담는다.
while(!queue.isEmpty()){
Document current = queue.poll();
if (current.priority == priorityQueue.peek()) {
priorityQueue.poll();
count++;
if (current.index == printDocIndex) {
sb.append(count).append("\n");
break;
}
} else {
queue.add(current);
}
}