개발 공부 기록

[Baekjoon 1966번/JAVA] 프린터 큐(Queue) 본문

PS/Implement

[Baekjoon 1966번/JAVA] 프린터 큐(Queue)

나만없서고냥이 2023. 10. 21. 13:41

Question

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

 

1966번: 프린터 큐

여러분도 알다시피 여러분의 프린터 기기는 여러분이 인쇄하고자 하는 문서를 인쇄 명령을 받은 ‘순서대로’, 즉 먼저 요청된 것을 먼저 인쇄한다. 여러 개의 문서가 쌓인다면 Queue 자료구조에

www.acmicpc.net

 


💡 Solution

큐를 이용해서 금방 해결할 수 있는 문제입니다. 

 

큐의 맨 앞의 값을 현재를 가르키는 current 변수로 두고, current 값을 인쇄할 수 있는 상태(= current 값이 큐의 최댓값일 때)라면 count 값을 1 증가시킵니다. 이때 해당 값의 인덱스가 M이라면 바로 출력을 진행합니다.

 

만일 current 위치의 값을 인쇄할 수 있는 상태가 아니라면, 해당 값을 맨 뒤로 보내줘야 하므로 큐의 맨 뒤에 해당 값을 추가합니다. 그리고 current는 다음 위치로 이동하게 되면서(= 다음 위치의 값을 가르키면서) 큐가 빈 상태이기 전까지 탐색하며 답을 구합니다.

 

💻 Code

package BaekJoon;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class BJ1966 {
	static int N;
	static int M;
	static Queue<Integer> queue;
	static Queue<Integer> indexQueue;

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int T = Integer.parseInt(br.readLine());
		
		for(int tc = 0; tc < T; tc++) {
			StringTokenizer st = new StringTokenizer(br.readLine(), " ");
			N = Integer.parseInt(st.nextToken());
			M = Integer.parseInt(st.nextToken());
			
			queue = new LinkedList<>();
			indexQueue = new LinkedList<>();
			
			st = new StringTokenizer(br.readLine(), " ");
			for(int i = 0; i < N; i++ ) {
				queue.offer(Integer.parseInt(st.nextToken()));
				indexQueue.offer(i);
			}
			getResult();
		}

	}
	
	public static void getResult() {
		int count = 0;
		
		while(!queue.isEmpty()) {
			int max = Collections.max(queue);
			int current = queue.poll();
			int currentIndex = indexQueue.poll();
			
			if(current == max) {
				count++;
				if(currentIndex == M) {
					System.out.println(count);
					break;
				}
				
			} else {
				queue.offer(current);
				indexQueue.offer(currentIndex);
			}
		}
	}
	
}