개발자-H 입니다.

BOJ - 프린터 큐 본문

Algorithm/문제 풀이

BOJ - 프린터 큐

개발자-H 2021. 9. 9. 07:37

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

 

1966번: 프린터 큐

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

www.acmicpc.net

 

  • 큐를 이용하여 주어진 조건대로 구현하면 된다
  • 예제 이해가 힘들었는데 간략하게 설명하자면
  • 예제
    • 6 0
    • 1 1 9 1 1 1
  • 문서의 개수는 6개이고 0번쨰에 있는 문서가 언제 출력 알려달라는 것이였다.
  • 여기서 0번째란 1 1 9 1 1 1 이므로 돌려보면
    • 1 9 1 1 1 1
    • 9 1 1 1 1 1 (출력)
    • 1 1 1 1 1 (출력)
    • 1 1 1 1 (출력)
    • 1 1 (출력)
    • 1 1 (출력)
    • 5번째 출력이 된다.

 

import java.io.*;
import java.util.*;


public class Main {
    public static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    public static void main(String[] args) throws Exception {
        int T = Integer.parseInt(br.readLine());

        while (T-- > 0) {
            String[] s = br.readLine().split(" ");
            int N = Integer.parseInt(s[0]);
            int target = Integer.parseInt(s[1]);

            StringTokenizer st = new StringTokenizer(br.readLine());
            Queue<Node> queue = new LinkedList<>();

            for (int i = 0; i < N; i++) {
                int priority = Integer.parseInt(st.nextToken());
                boolean curious = i == (target);
                queue.offer(new Node(curious, priority));
            }

            int printCount = 0;
            while (!queue.isEmpty()) {
                //맨 앞의 노드
                Node peek = queue.peek();

                boolean existPriorityNode = false;
                Iterator<Node> iterator = queue.iterator();
                while (iterator.hasNext()) {
                    Node next = iterator.next();
                    if (peek.priority < next.priority) {
                        existPriorityNode = true;
                        break;
                    }
                }

                // 우선순위높은 노드가 있을 경우
                if (existPriorityNode) {
                    queue.offer(queue.poll());
                    continue;
                }

                //출력
                printCount++;
                Node poll = queue.poll();

                //궁금했던 노드이면 종료
                if (poll.curiousDocument) {
                    break;
                }
            }

            System.out.println(printCount);
        }
    }

    static class Node {
        //궁금한 노드인지 여부
        public boolean curiousDocument;
        
        //우선순위
        public int priority;

        public Node(boolean curiousDocument, int priority) {
            this.curiousDocument = curiousDocument;
            this.priority = priority;
        }
    }
}
Comments