백준 14891번: 톱니바퀴 [Python]

골드 V 골드 V

문제

톱니바퀴

풀이

문제에서 요구하는 사항을 잘 구현하면 됩니다. 저는 Gear 클래스를 만들어서 기어를 회전시키면서 왼쪽, 오른쪽, 위쪽의 극을 쉽게 구할 수 있도록 했습니다. 기어를 회전할 때는 리스트를 회전하는게 아니라 기준이 되는 인덱스를 더하고 빼도록 구현했습니다.

톱니를 돌릴 때는 해당 톱니를 기준으로 좌우로 뻗어나가면서 회전 방향을 결정한 후에 나중에 한꺼번에 회전하도록 했습니다.

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from typing import Iterable


class Gear:
    def __init__(self, poles: Iterable[int]):
        """
        poles should satisfy the following conditions:

        0 represents N pole and 1 represents S pole.
        poles[0] represents the pole of the upmost tooth.
        poles[i] represents the pole of the i-th tooth clockwise from the 0-th tooth.

        """
        self.poles = tuple(poles)
        self.idx = 6

    @property
    def leftPole(self):
        return self.poles[self.idx]

    @property
    def rightPole(self):
        return self.poles[(self.idx + 4) % 8]

    @property
    def upPole(self):
        return self.poles[(self.idx + 2) % 8]

    def rotateClockwise(self):
        self.idx = (self.idx - 1) % 8

    def rotateCounterclockwise(self):
        self.idx = (self.idx + 1) % 8


gears = [Gear(map(int, list(input()))) for _ in range(4)]

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

    rotate = [0] * 4
    rotate[num] = direction

    for i in range(num - 1, -1, -1):
        if gears[i].rightPole != gears[i + 1].leftPole and rotate[i + 1]:
            rotate[i] = -rotate[i + 1]
    for i in range(num + 1, 4):
        if gears[i - 1].rightPole != gears[i].leftPole and rotate[i - 1]:
            rotate[i] = -rotate[i - 1]

    for i in range(4):
        if rotate[i] == 1:
            gears[i].rotateClockwise()
        elif rotate[i] == -1:
            gears[i].rotateCounterclockwise()

score = 0
weight = 1
for i in range(4):
    if gears[i].upPole == 1:
        score += weight
    weight <<= 1

print(score)

백준 14891번: 톱니바퀴 [Python]