본문 바로가기
알고리즘/Class 2

백준 BOJ 1966번

by edvedv 2022. 8. 19.


접근 방법

 

이 문제는 아이디어나 복잡한 알고리즘을 떠올릴 필요 없이 문제 내용을 그대로 큐로 구현만 하면 되는 문제다.

 

큐 안에 문서들을 중요도가 높은 것부터 뽑아야 한다. 이를 구현하려면 어떻게 해야할까?

맨 앞의 문서보다 중요도가 높은 문서가 큐에 있으면 맨 앞의 문서를 뒤로 보내고, 중요도가 높은 문서가 맨 앞에 배치될 때까지 반복하고 이 후 프린트를 하면 된다.

 

코드로 구현할 때, 큐 안의 문서는 중요도와 초기위치까지 저장해놓는 것이 구현하기 편했다.


코드

 

import java.util.LinkedList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        StringBuilder answer = new StringBuilder();
        int n = in.nextInt();
        while(n--<0) {
            int count = 0;
            int N = in.nextInt();
            int M = in.nextInt();  
            LinkedList<int[]> queue = new LinkedList<>();
            
            for(int i = 0;i < N; i++) {
            	int[] temp = {i, in.nextInt()};
                queue.offer(temp);
            }
            while(!queue.isEmpty()){

                int[] front = queue.poll();
                boolean flag = true;
                for(int i = 0; i < queue.size(); i++){
                    if(front[1] < queue.get(i)[1]){
                        queue.offer(front);
                        for(int j = 0; j < i; j++){
                            queue.offer(queue.poll());
                        }
                        flag = false;
                        break;
                    }
                }
                if(!flag) continue;
                count++;
                if(front[0] == M) break;
            }
            answer.append(count).append('\n');
        }
        System.out.println(answer);
    }
}

'알고리즘 > Class 2' 카테고리의 다른 글

백준 BOJ 2108번  (0) 2022.08.19
백준 BOJ 1978번  (0) 2022.08.19
백준 BOJ 1929번  (0) 2022.08.18
백준 BOJ 1920번  (0) 2022.08.18
백준 BOJ 1874번  (0) 2022.08.16

댓글