알고리즘 공부
백준 컨베이어 밸트 위의 로봇
컴퓨터과학
2024. 2. 17. 20:49
https://www.acmicpc.net/problem/20055
20055번: 컨베이어 벨트 위의 로봇
길이가 N인 컨베이어 벨트가 있고, 길이가 2N인 벨트가 이 컨베이어 벨트를 위아래로 감싸며 돌고 있다. 벨트는 길이 1 간격으로 2N개의 칸으로 나뉘어져 있으며, 각 칸에는 아래 그림과 같이 1부
www.acmicpc.net
문제는 쉬운편이였습니다. 다만 문제를 이해하는게 조금 난이도가 있었고요 로봇을 내리는 상황을 정확하게 이해해야합니다. n번째의 로봇이 내린다. 라는걸 이해를 잘 해야합니다.
import java.util.*;
public class Main {
private int durability;
private boolean robot;
public Main(int durability, boolean robot) {
this.durability = durability;
this.robot = robot;
}
public void setDurability(int durability) {
this.durability = durability;
}
public void setRobot(boolean robot) {
this.robot = robot;
}
public int getDurability() {
return this.durability;
}
public boolean hasRobot() {
return this.robot;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int k = scan.nextInt();
Main belt[] = new Main[n * 2];
for (int i = 0; i < n * 2; i++) {
int tmp = scan.nextInt();
belt[i] = new Main(tmp, false);
}
int gcnt = 0;
while (true) {
// Step 1: Move the belt
Main tmp = belt[n * 2 - 1];
for (int i = n * 2 - 1; i > 0; i--) {
belt[i] = belt[i - 1];
}
belt[0] = tmp;
// Step 1.5: Remove robot at position n-1 (if any)
belt[n - 1].setRobot(false);
// Step 2: Move the robots
for (int i = n - 2; i >= 0; i--) { // 로봇 이동 가능성 검사 범위 수정
if (belt[i].hasRobot() && !belt[i + 1].hasRobot() && belt[i + 1].getDurability() > 0) {
belt[i].setRobot(false);
belt[i + 1].setRobot(true);
belt[i + 1].setDurability(belt[i + 1].getDurability() - 1);
if (i + 1 == n - 1) { // n-1 위치에 도달한 로봇 즉시 내리기
belt[i + 1].setRobot(false);
}
}
}
// Step 3: Add a new robot
if (belt[0].getDurability() > 0 && !belt[0].hasRobot()) {
belt[0].setRobot(true);
belt[0].setDurability(belt[0].getDurability() - 1);
}
// Step 4: Check for broken belts
int brokenCount = 0;
for (Main m : belt) {
if (m.getDurability() == 0) {
brokenCount++;
}
}
gcnt++;
if (brokenCount >= k) {
System.out.println(gcnt);
break;
}
}
}
}