본문 바로가기
Algorithm (PS)/백준

[백준] 1966. 프린터 큐 (Java) [Queue + PrioirtyQueue]

by 태크민 2023. 7. 5.

문제

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

 

1966번: 프린터 큐

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

www.acmicpc.net

 

 

사용한 알고리즘

큐(Queue) + 우선순위 큐(PriorityQueue)

 

 

풀이

큐(Queue)에 중요도(int)와 궁금한 문서인지 flag(boolean)을 저장하고,

우선순위큐(PriorityQueue)에 가장 높은 중요도를 저장하였다.

그런다음 큐에서 하나씩 아이템을 빼서 우선순위 큐에서  뺀 가장 높은 중요도 비교하여 문제를 풀었다.

 

자세한건 코드를 확인해보자.

 

코드

import java.util.*;

public class Main {
    static int t = 0;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        t = sc.nextInt();

        while (t > 0) {
            t--;
            int N, M;
            N = sc.nextInt();
            M = sc.nextInt();
            Queue<Pair> q = new LinkedList<Pair>();
            PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());

            //입력
            for(int i=0; i<N; i++){
                int itemPriority= sc.nextInt(); //각 문서의 중요도
                boolean isCurious = false; //궁금한 문서 표시 flag
                if(i==M){
                    isCurious =true;
                }
                q.add(new Pair(itemPriority, isCurious)); //queue에 저장
                pq.add(itemPriority);
            }

            int answer=0;
            //검사
            while(!q.isEmpty()){
                Pair item =q.peek();
                int highPriority =  pq.peek();

                //큐에서 뺀게 중요도가 가장 높은 아이템이라면
                if(item.priority == highPriority){
                    pq.remove();
                    q.remove();
                    answer++;
                    if(item.flag){ // 궁금한 문서라면 출력
                        System.out.println(answer);
                        break;
                    }
                }
                //큐에서 뺀게 중요도가 가장 높은 아이템이 아니라면
                else{
                    q.remove();
                    q.add(item);
                }
            }
        }
    }

    static class Pair{
        int priority;
        boolean flag;

        public Pair(int priority, boolean flag) {
            this.priority = priority;
            this.flag = flag;
        }
    }
}

 

필자는 PriorityQueue와 Queue를 이용해서 풀었지만,

순수하게 Queue를 이용한 풀이도 있는 것 같다.

https://st-lab.tistory.com/201

 

 

Queue 개념

https://coding-factory.tistory.com/602

 

[Java] 자바 Queue 클래스 사용법 & 예제 총정리

Queue란? Queue의 사전적 의미는 무엇을 기다리는 사람, 차량 등의 줄 혹은 줄을 서서 기다리는 것을 의미하는데 이처럼 줄을 지어 순서대로 처리되는 것이 큐라는 자료구조입니다. 큐는 데이터를

coding-factory.tistory.com

PriorityQueue 개념

https://coding-factory.tistory.com/603

 

[Java] PriorityQueue(우선순위 큐) 클래스 사용법 & 예제 총정리

우선순위 큐(Priority Queue)란? 일반적으로 큐는 데이터를 일시적으로 쌓아두기 위한 자료구조로 스택과는 다르게 FIFO(First In First Out)의 구조 즉 먼저 들어온 데이터가 먼저 나가는 구조를 가집니다

coding-factory.tistory.com