문제
여러분도 알다시피 여러분의 프린터 기기는 여러분이 인쇄하고자 하는 문서를 인쇄 명령을 받은 ‘순서대로’, 즉 먼저 요청된 것을 먼저 인쇄한다. 여러 개의 문서가 쌓인다면 Queue 자료구조에 쌓여서 FIFO - First In First Out - 에 따라 인쇄가 되게 된다. 하지만 상근이는 새로운 프린터기 내부 소프트웨어를 개발하였는데, 이 프린터기는 다음과 같은 조건에 따라 인쇄를 하게 된다.
- 현재 Queue의 가장 앞에 있는 문서의 ‘중요도’를 확인한다.
- 나머지 문서들 중 현재 문서보다 중요도가 높은 문서가 하나라도 있다면, 이 문서를 인쇄하지 않고 Queue의 가장 뒤에 재배치 한다. 그렇지 않다면 바로 인쇄를 한다.
예를 들어 Queue에 4개의 문서(A B C D)가 있고, 중요도가 2 1 4 3 라면 C를 인쇄하고, 다음으로 D를 인쇄하고 A, B를 인쇄하게 된다.
여러분이 할 일은, 현재 Queue에 있는 문서의 수와 중요도가 주어졌을 때, 어떤 한 문서가 몇 번째로 인쇄되는지 알아내는 것이다. 예를 들어 위의 예에서 C문서는 1번째로, A문서는 3번째로 인쇄되게 된다.
입력
첫 줄에 테스트케이스의 수가 주어진다. 각 테스트케이스는 두 줄로 이루어져 있다.
테스트케이스의 첫 번째 줄에는 문서의 개수 N(1 ≤ N ≤ 100)과, 몇 번째로 인쇄되었는지 궁금한 문서가 현재 Queue에서 몇 번째에 놓여 있는지를 나타내는 정수 M(0 ≤ M < N)이 주어진다. 이때 맨 왼쪽은 0번째라고 하자. 두 번째 줄에는 N개 문서의 중요도가 차례대로 주어진다. 중요도는 1 이상 9 이하의 정수이고, 중요도가 같은 문서가 여러 개 있을 수도 있다.
출력
각 테스트 케이스에 대해 문서가 몇 번째로 인쇄되는지 출력한다.
우선순위 큐를 사용하면 더 간단하지 않을까 생각했는데, 우선순위가 높지 않은 원소를 계속 뒤로 보내줘야 하기 때문에 그냥 큐를 사용하였다.
문서의 index와 우선순위를 관리하기 위해 Document 클래스를 생성하였다.
또 가장 높은 우선순위를 찾기 위해 static 변수로 max를 담고, 해당 index를 우선순위로 하는 수만큼 1씩 더해주었다.
queue에 document를 담은 후, M에 해당하는 문서가 출력될 때까지 while문을 반복한다.
queue의 peek에 있는 원소의 우선순위가 max보다 작다면 poll하여 뒤에 offer한다.
max를 찾으면 poll하고, 해당 우선순위 값을 max 배열에서 1씩 감소시킨 후, cnt(인쇄 순서)를 1씩 더한다.
package Silver.s3;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Document {
static int[] max = new int[10];
int index;
int priority;
public Document(int index, int priority) {
this.index = index;
this.priority = priority;
}
}
public class BOJ_1966_PrinterQueue {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int t = 0; t < T; t++) {
int N = sc.nextInt();
int M = sc.nextInt();
Queue<Document> queue = new LinkedList<>();
Arrays.fill(Document.max, 0); // max 초기화
for (int i = 0; i < N; i++) {
int priority = sc.nextInt();
Document.max[priority]++;
queue.offer(new Document(i, priority));
}
int cnt = 1;
int max = 0;
while (true) {
for (int i = 9; i >= 1; i--)
if (Document.max[i] > 0) {
max = i;
break;
} // queue에 있는 가장 큰 priority 찾기
if (queue.peek().priority < max) {
queue.offer(queue.poll()); // max보다 우선순위가 작으면 poll해서 다시 offer
} else {
if (queue.peek().index == M)
break; // 우선순위가 같은 것 중에 index가 M이면 해당 cnt가 answer
Document doc = queue.poll(); // 우선순위가 가장 높은 것을 poll
Document.max[doc.priority]--; // 해당 우선순위를 감소시켜줌
cnt++; // 인쇄 순서
}
}
System.out.println(cnt);
}
}
}
'문제 풀이 > BOJ' 카테고리의 다른 글
[백준] 17276 배열 돌리기 (자바/Java) (0) | 2022.08.22 |
---|---|
[백준] 10866 - 덱 Deque (자바/Java) (0) | 2022.08.18 |
[백준] 17298 - 오큰수 (자바/Java) (0) | 2022.08.18 |
[백준] 1874 - 스택수열 (자바/Java) (0) | 2022.08.18 |
[백준] 2559 - 수열 (자바/Java) (0) | 2022.08.18 |