[BOJ] 14891 톱니바퀴

시뮬레이션


시뮬레이션 유형은 알고리즘에 비해 구현 난이도가 높다. 파이썬 실력이 중요해보인다.

해당 문제는 톱니바퀴가 단순히 4개라서 뇌를 빼고 if-else로만 구현이 가능할 것 같아서 빠르게 if-else문을 많이 사용하여 아래와 같이 구현했다.

톱니바퀴의 회전은 파이썬의 list slicing을 이용하여 구현했다.

import sys

def rotate(li, di):
    if di == 1:     # 오른쪽 방향
        return li[-1:] + li[:-1]
    return li[1:] + li[:1]  # 왼쪽 방향

gears = []
for _ in range(4):
    gears.append(list(sys.stdin.readline().rstrip()))
K = int(sys.stdin.readline().rstrip())

for _ in range(K):
    gear_n, direction = map(int, sys.stdin.readline().split())
    if gear_n == 1:
        if gears[0][2] != gears[1][6]:  # 1,2 둘이 다르면 회전
            if gears[1][2] != gears[2][6]:  # 2,3 둘이 다르면 회전
                if gears[2][2] != gears[3][6]:
                    gears[3] = rotate(gears[3], -direction)
                gears[2] = rotate(gears[2], direction)
            gears[1] = rotate(gears[1], -direction)
        gears[0] = rotate(gears[0], direction)
    elif gear_n == 2:
        if gears[0][2] != gears[1][6]:  # 1,2
            gears[0] = rotate(gears[0], -direction)
        if gears[1][2] != gears[2][6]:  # 2,3
            if gears[2][2] != gears[3][6]:   # 3,4
                gears[3] = rotate(gears[3], direction)
            gears[2] = rotate(gears[2], -direction)
        gears[1] = rotate(gears[1], direction)
    elif gear_n == 3:
        if gears[2][2] != gears[3][6]:  # 3,4
            gears[3] = rotate(gears[3], -direction)
        if gears[1][2] != gears[2][6]:  # 2,3
            if gears[0][2] != gears[1][6]:   # 1,2
                gears[0] = rotate(gears[0], direction)
            gears[1] = rotate(gears[1], -direction)
        gears[2] = rotate(gears[2], direction)
    else:
        if gears[2][2] != gears[3][6]:  # 3,4
            if gears[1][2] != gears[2][6]:  # 2,3
                if gears[0][2] != gears[1][6]:  # 1,2
                    gears[0] = rotate(gears[0], -direction)
                gears[1] = rotate(gears[1], direction)
            gears[2] = rotate(gears[2], -direction)
        gears[3] = rotate(gears[3], direction)

answer = 0
for i in range(4):
    if gears[i][0] == '1':
        answer += (2**i)*1
print(answer)

태그:

카테고리:

업데이트: