곽로그

[백준 1021] 회전하는 큐 본문

알고리즘/백준

[백준 1021] 회전하는 큐

일도이동 2020. 1. 12. 23:07
반응형

 

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
 
public class Main {
    public static Deque<Integer> rotateQueue = new LinkedList<Integer>();
 
    public static int operationFirst() {
        return rotateQueue.pollFirst();
    }
 
    public static void operationLeft() {
        // 왼쪽으로 한칸 이동
        int left = rotateQueue.pollFirst();
        rotateQueue.addLast(left);
    }
 
    public static void operationRight() {
        // 오른쪽으로 한칸 이동
        int right = rotateQueue.pollLast();
        rotateQueue.addFirst(right);
    }
 
    public static int getIndex(int number) {
        Iterator<Integer> ir = rotateQueue.iterator();
        int index = 0;
        while (ir.hasNext()) {
            int num = ir.next();
            if (number == num) {
                return index;
            }
            index++;
        }
        return -1;
    }
 
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        int M = in.nextInt();
        int count = 0;
 
        for (int i = 1; i <= N; i++) {
            rotateQueue.addLast(i);
        }
 
        for (int i = 0; i < M; i++) {
            int wannaKnow = in.nextInt();
 
            // 알고싶은 숫자의 현재 큐에서의 위치
            int index = getIndex(wannaKnow);
            //기준점
            int benchMark = (rotateQueue.size() / 2) ;
            
            //기준점보다 왼쪽이면 왼쪽으로 이동, 기준점보다 오늘쪽이면 오른쪽으로 이동
            if (index <=benchMark) {
                while (rotateQueue.peek() != wannaKnow) {
                    operationLeft();
                    count++;
                }
                operationFirst();
            } else {
                while (rotateQueue.peek() != wannaKnow) {
                    operationRight();
                    count++;
                }
                operationFirst();
            }
 
        }
        System.out.println(count);
 
    }
}​
반응형

'알고리즘 > 백준' 카테고리의 다른 글

[백준 2164] 카드2  (0) 2020.01.20
[백준 10799] 쇠막대기  (0) 2020.01.19
[백준 10866] 덱  (0) 2020.01.12
[백준1966] 프린터 큐  (0) 2020.01.12
[백준 10845] 큐  (0) 2020.01.04
Comments