Home (Python)(JAVA)[백준] 프린터 큐
Post
Cancel

(Python)(JAVA)[백준] 프린터 큐

1966번: 프린터 큐

문제 풀이


해시 테이블처럼 index 리스트를 만들어서 문서를 구분하였다.

소스 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
t = int(input())
 
for _ in range(t):
    n, m = map(int, input().split()) # 4, 2 
    priority = list(map(int, input().split())) # [1 2 3 4] 2341 3412 4123 123 231 312 
    idx = [i for i in range(n)] # [0, 1, 2, 3] [0 1 target 3] 1t30 t301 301t 01t 1t0 t01 
    idx[m] = 'target' # idx[2] = 'target'
    cnt = 0 # 1 2
 
    while priority:
        if priority[0] == max(priority):    
            cnt += 1
            if idx[0] == 'target':
                print(cnt)
                break
            priority.pop(0)
            idx.pop(0)
        else:
            priority.append(priority.pop(0))
            idx.append(idx.pop(0))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.util.Scanner;
import java.util.LinkedList;
 
public class PrinterQueue {
	public static void main(String[] args) {
		
		Scanner in = new Scanner(System.in);
		StringBuilder sb = new StringBuilder();
		
		int T = in.nextInt();	// 테스트 케이스 
 
		while (T-- > 0) { // 증감연산자 -- (나중에 - 적용)
			
			int N = in.nextInt();
			int M = in.nextInt();
			
			LinkedList<int[]> q = new LinkedList<>();	// Queue로 활용 할 연결리스트. <> 타입 선언 생략
 
			for (int i = 0; i < N; i++) {
				// {초기 위치, 중요도}
				q.offer(new int[] { i, in.nextInt() });
			}
 
			int count = 0;
			
			while (!q.isEmpty()) {	// 한 케이스에 대한 반복문
				
				int[] front = q.poll();	// 가장 첫 원소
				boolean isMax = true;	// front 원소가 가장 큰 원소인지를 판단하는 변수
				
				// 큐에 남아있는 원소들과 중요도를 비교 
				for(int i = 0; i < q.size(); i++) {
					
					// 처음 뽑은 원소보다 큐에 있는 i번째 원소가 중요도가 클 경우 
					if(front[1] < q.get(i)[1]) {
						
						// 뽑은 원소 및 i 이전의 원소들을 뒤로 보낸다.
						q.offer(front);
						for(int j = 0; j < i; j++) {
							q.offer(q.poll());
						}
						
						// front원소가 가장 큰 원소가 아니였으므로 false를 하고 탐색을 마침
						isMax = false;
						break;
					}
				}
				
				// front 원소가 가장 큰 원소가 아니였으므로 다음 반복문으로 넘어감
				if(isMax == false) {
					continue;
				}
				
				// front 원소가 가장 큰 원소였으므로 해당 원소는 출력해야하는 문서다.
				count++;
				if(front[0] == M) {	// 찾고자 하는 문서라면 해당 테스트케이스 종료
					break;
				}
			}
 
			sb.append(count).append('\n');
		}
		System.out.println(sb);
	}
}

This post is licensed under CC BY 4.0 by the author.