본문 바로가기
문제풀이/백준

[JAVA] BOJ 백준 1021번 - 회전하는 큐

by 그적 2023. 2. 12.

목차

  • 문제
  • 내가 푼 방법
  • 자바 코드
  • 결과 및 회고

1. 문제

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

 

1021번: 회전하는 큐

첫째 줄에 큐의 크기 N과 뽑아내려고 하는 수의 개수 M이 주어진다. N은 50보다 작거나 같은 자연수이고, M은 N보다 작거나 같은 자연수이다. 둘째 줄에는 지민이가 뽑아내려고 하는 수의 위치가

www.acmicpc.net


2. 내가 푼 방법

문제 명칭 때문에 큐가 바로 떠오르지만, LinkedList를 사용하면 아주 쉽게 풀 수 있는 문제이다.

- 첫 번째 원소를 뽑아낼 때 사용하는 pollFirst() 메서드

- 왼쪽으로 한 칸 이동할 때 사용하는 pollFirst() 메서드 + addLast() 메서드

- 오른쪽으로 한 칸 이동할 때 사용하는 pollLast() 메서드 + addFirst() 메서드

 

이제 남은 것은 뽑아내려고 하는 원소가 몇 번째 들어있는지 확인해야 하는 것인데,

이때 사용할 수 있는 메서드는 indexOf() 메서드이다.

 

따라서 뽑아내려고 하는 원소의 순서가 큐 사이즈 절반보다 작다면 왼쪽으로 이동, 크다면 오른쪽으로 이동을 하면 된다.


3. 자바 코드

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

class Main {
    static LinkedList<Integer> queue;
    static int[] arr;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        StringTokenizer st = new StringTokenizer(br.readLine());
        int size = Integer.parseInt(st.nextToken());
        int N = Integer.parseInt(st.nextToken());

        // queue 초기화
        queue = new LinkedList<>();
        for (int i = 1; i <= size; i++) {
            queue.add(i);
        }

        // arr 초기화
        arr = new int[N];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < N; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }

        // 솔루션
        int result = 0;
        for (int i = 0; i < N; i++) {
            result += solve(arr[i]);
        }

        bw.write(String.valueOf(result));

        br.close();
        bw.flush();
        bw.close();
    }

    public static int solve(int find) {
        int idx = queue.indexOf(find);
        int half = queue.size() / 2;

        int count = 0;
        if (idx <= half) {
            while (!queue.isEmpty()) {
                int head = queue.pollFirst();

                if (head == find) break;

                count++;
                queue.addLast(head);
            }
        }
        else {
            while (!queue.isEmpty()) {
                int tail = queue.pollLast();
                count++;

                if (tail == find) break;

                queue.addFirst(tail);
            }
        }
        return count;
    }
}

4. 결과 및 회고

결과는 성공ㅎㅎ

하지만 컬렉션 범위를 Queue나 Deque로 한정 짓지 말고 LinkedList를 사용하는 버릇을 들자.

댓글