알고리즘/스택, 큐

[백준] 1966번 프린터 큐 #Java

VIPeveloper 2022. 5. 7. 18:00
728x90
반응형
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

class Paper{

    int idx;
    int prior;

    Paper(int idx,int prior){
        this.idx = idx;
        this.prior = prior;
    }

}

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        int test_case = Integer.parseInt(br.readLine());

        for (int i = 0; i < test_case; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine()," ");
            int n = Integer.parseInt(st.nextToken());
            int m = Integer.parseInt(st.nextToken());
            Queue<Paper> q = new LinkedList<>();
            // 우선순위큐 내림차순 정렬.
            PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());
            st = new StringTokenizer(br.readLine()," ");
            for (int j = 0; j < n; j++) {
                int prior = Integer.parseInt(st.nextToken());
                q.offer(new Paper(j,prior));
                pq.offer(prior);
            }

            System.out.println(solution(q, pq, m));

        }
    }

    private static int solution(Queue<Paper> q, PriorityQueue<Integer> pq,int m) {
        int cnt = 1;
        while (true){
            while (pq.peek() != q.peek().prior){
                q.offer(q.poll());
            }
            if(q.peek().idx==m){
                break;
            }
            q.poll();
            pq.poll();
            cnt++;  // 번째 업데이트.
        }
        return cnt;
    }
}
728x90
반응형