[백준 14891] 톱니바퀴

코뉴·2022년 4월 12일
0

백준🍳

목록 보기
142/149

🥚문제

https://www.acmicpc.net/problem/14891

  • 구현
  • 시뮬레이션


🥚입력/출력


🍳코드

import sys
from collections import deque
input = sys.stdin.readline

def rotate_gear(target, direction):
    if visited[target]:
        return
    
    # 현재 target 방문 표시
    visited[target] = True
    # 왼쪽 기어 확인
    if target - 1 >= 0:
        # 맞닿은 극이 다르면 반대방향으로 회전
        # target의 9시방향과 target-1의 3시방향 비교
        if gears[target][6] != gears[target-1][2]:
            rotate_gear(target-1, -direction)
    # 오른쪽 기어 확인
    if target + 1 < 4:
        if gears[target][2] != gears[target+1][6]:
            rotate_gear(target+1, -direction)
    
    # 현재 gear 회전
    gears[target].rotate(direction)

gears = [deque(list(input().strip())) for _ in range(4)]

for _ in range(int(input())):
    target, direction = map(int, input().split())
    target -= 1

    visited = [False]*4
    rotate_gear(target, direction)

# 점수 계산
score = 0
for i in range(4):
    score += int(gears[i][0]) * (2**i)
print(score)

🧂아이디어

구현

  • 각각의 톱니바퀴는 deque자료구조로 표현한다. deque의 rotate함수를 이용하여 톱니바퀴의 회전을 쉽게 구현할 수 있다.
    rotate(1)은 시계방향, rotate(-1)은 반시계방향으로 deque 내의 원소들을 회전시킨다.

  • n번째 톱니바퀴가 회전할 때, 인접한 (n+1), (n-1)번째 톱니바퀴들도 회전하는지 체크해줘야 한다.

  • n번째 톱니바퀴를 gears[n]이라고 하자.
  • 왼쪽에 있는 gears[n-1]이 gears[n]과 반대방향으로 회전하는지 알아보기 위해서는
    gears[n-1]의 3시방향 극과 gears[n]의 9시방향 극을 체크하면 된다.
    • check if gears[n][6] != gears[n-1][2]
  • 오른쪽에 있는 gears[n+1]이 gears[n]과 반대방향으로 회전하는지 알아보기 위해서는
    gears[n+1]의 9시방향 극과 gears[n]의 3시방향 극을 체크하면 된다.
    • check if gears[n][2] != gears[n+1][6]
  • 이를 rotate_gear 재귀함수로 구현했다.
profile
코뉴의 도딩기록

0개의 댓글