in.add()

[20055] 컨베이어 벨트 위의 로봇 본문

Algorithm/BOJ

[20055] 컨베이어 벨트 위의 로봇

idan 2021. 10. 15. 23:03

문제 링크 : https://www.acmicpc.net/problem/20055

 

20055번: 컨베이어 벨트 위의 로봇

길이가 N인 컨베이어 벨트가 있고, 길이가 2N인 벨트가 이 컨베이어 벨트를 위아래로 감싸며 돌고 있다. 벨트는 길이 1 간격으로 2N개의 칸으로 나뉘어져 있으며, 각 칸에는 아래 그림과 같이 1부

www.acmicpc.net

 

문제 해결 방법

원형 큐와 비슷하게 작동하도록 구현했다.

 

 

import java.util.Scanner;

public class Main {
    static int N, K, left, right;
    static int[] belt;
    static boolean on[];

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();
        K = sc.nextInt();
        belt = new int[2 * N];
        on = new boolean[N];
        for (int i = 0; i < 2 * N; i++) {
            belt[i] = sc.nextInt();
        }
        left = 0;
        right = N;

        int cnt = 0;
        while (K > 0) {
            cnt++;
            moveBelt();
            moveRobot();
            newRobot();
        }
        System.out.println(cnt);
    }

    public static void moveBelt() {
        left--;
        right--;
        if (left == -1) {
            left = 2 * N - 1;
        }
        if (right == -1) {
            right = 2 * N - 1;
        }

        for (int i = N - 2; i >= 0; i--) {
            if (on[i]) {
                on[i] = false;
                if (i + 1 < N - 1) {
                    on[i + 1] = true;
                }
            }
        }
    }

    public static void moveRobot() {
        for (int i = N - 2; i >= 0; i--) {
            if (on[i]) {
                int next = left + i + 1;
                if (next >= 2 * N) {
                    next -= 2 * N;
                }
                if (!on[i + 1] && belt[next] >= 1) {
                    on[i] = false;
                    if (i + 1 < N - 1) {
                        on[i + 1] = true;
                    }
                    belt[next]--;
                    if (belt[next] == 0) {
                        K--;
                    }
                }
            }
        }
    }

    public static void newRobot() {
        if (!on[0] && belt[left] > 0) {
            on[0] = true;
            belt[left]--;
            if (belt[left] == 0) {
                K--;
            }
        }
    }
}

'Algorithm > BOJ' 카테고리의 다른 글

[2293] 동전 1  (0) 2021.10.19
[14442] 벽 부수고 이동하기 2  (0) 2021.10.17
[1991] 트리 순회  (0) 2021.10.14
[2579] 계단 오르기  (0) 2021.10.13
[2206] 벽 부수고 이동하기  (0) 2021.10.11
Comments