20055번: 컨베이어 벨트 위의 로봇 (acmicpc.net)
20055번: 컨베이어 벨트 위의 로봇
길이가 N인 컨베이어 벨트가 있고, 길이가 2N인 벨트가 이 컨베이어 벨트를 위아래로 감싸며 돌고 있다. 벨트는 길이 1 간격으로 2N개의 칸으로 나뉘어져 있으며, 각 칸에는 아래 그림과 같이 1부
www.acmicpc.net
알고리즘 : 시뮬레이션
문제를 이해하고 그대로 구현하는 문제
문제가 복잡해지면서 함수로 문제를 분할해서 풀기 시작했다.
- Javascript
function solution() {
let input = require("fs")
.readFileSync("input.txt")
.toString()
.split("\n")
.map((val) => val.trim());
let [n, k] = input
.shift()
.split(" ")
.map((v) => +v);
let durability = input
.shift()
.split(" ")
.map((v) => +v);
let robots = new Array(n).fill(0);
let ans = 0;
const rotation = (durability, robots) => {
let temp = durability.pop();
durability.unshift(temp);
robots.pop();
robots.unshift(0);
if (robots[n - 1] === 1) robots[n - 1] = 0;
};
const moveRobot = (durability, robots) => {
for (let i = robots.length - 2; i >= 0; i--) {
if (robots[i] && durability[i + 1] >= 1 && !robots[i + 1]) {
durability[i + 1]--;
robots[i] = 0;
robots[i + 1] = 1;
}
}
if (robots[n - 1] === 1) robots[n - 1] = 0;
};
while (1) {
if (durability.filter((v) => v === 0).length >= k) {
console.log(ans);
break;
}
ans++;
rotation(durability, robots);
moveRobot(durability, robots);
if (robots[0] === 0 && durability[0] > 0) {
robots[0] = 1;
durability[0]--;
}
}
}
solution();
- Python
import sys
sys.stdin = open("baekjoon/20055/input.txt","r")
input = sys.stdin.readline
from collections import deque
n, k = map(int, input().split())
belt = deque(list(map(int, input().split())))
robot = deque([0]*n)
res = 0
while 1:
print(belt)
print(robot)
belt.rotate(1)
robot.rotate(1)
robot[-1]=0 #로봇이 내려가는 부분이니 0
if sum(robot): #로봇이 존재하면
for i in range(n-2, -1, -1): #로봇 내려가는 부분 인덱스 i-1 이므로 그 전인 i-2부터
if robot[i] == 1 and robot[i+1] == 0 and belt[i+1]>=1:
robot[i+1] = 1
robot[i] = 0
belt[i+1] -= 1
robot[-1]=0 #이 부분도 로봇 out -> 0임
if robot[0] == 0 and belt[0]>=1:
robot[0] = 1
belt[0] -= 1
res += 1
if belt.count(0) >= k:
break
print(res)
'코딩테스트(알고리즘) > baekjoon' 카테고리의 다른 글
[baekjoon] 3190 뱀 (Javascript,Python) (0) | 2023.03.15 |
---|---|
[baekjoon] 14499 주사위 굴리기 (Javascript,Python) (0) | 2023.03.14 |
[baekjoon] 14888 연산자 끼워넣기 (Javascript,Python) (0) | 2023.03.10 |
[baekjoon] 1520 내리막 길 (Javascript,Python) (0) | 2023.03.03 |
[baekjoon] 1987 알파벳 (Javascript,Python) (0) | 2023.03.02 |