happy318
팽도리블로그
happy318
전체 방문자
오늘
어제
  • 전체글 (252)
    • 공부 (5)
      • Algorithm 정리 (0)
      • 논문리뷰 (1)
      • C++ (2)
      • Python (2)
      • Java (0)
      • Back-end (0)
      • Front-end (0)
      • Embedded (0)
    • 코딩테스트 (218)
      • Python 문제풀이 (100)
      • C++ 문제풀이 (108)
      • Python template (9)
      • C++ template (1)
    • 일상 (20)
      • 맛집 (13)
      • 쇼핑 (5)
      • 아무 일상 (2)
    • 게임 (9)
      • 메이플스토리 (9)

최근 글

인기 글

hELLO · Designed By 정상우.
happy318

팽도리블로그

코딩테스트/Python 문제풀이

[백준] 톱니바퀴

2022. 7. 26. 22:19

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

 

14891번: 톱니바퀴

총 8개의 톱니를 가지고 있는 톱니바퀴 4개가 아래 그림과 같이 일렬로 놓여져 있다. 또, 톱니는 N극 또는 S극 중 하나를 나타내고 있다. 톱니바퀴에는 번호가 매겨져 있는데, 가장 왼쪽 톱니바퀴

www.acmicpc.net

구현 문제입니다.

 

우선 문제부터 간단하게 요약하면, 

톱니 바퀴가 4개 있고, 각각 8개의 톱니를 가집니다. 이 때, 톱니들은 N, S극을 가집니다. 톱니는 바로 옆의 톱니와 붙어있는 곳의 극(N,S)가 다르면, 옆의 톱니와 반대방향, 같다면, 움직이지 않습니다. 이 때, 톱니바퀴를 회전시킨 방법이 주어지면, 최종적으로 톱니바퀴가 어떤 상태인지를 통해 구한 점수를 return 해야 합니다.

 

<Solution>

직접 톱니바퀴 class와 rotate 할수 있도록 구성하여, 문제를 해결하였습니다. 

 

특정 톱니바퀴의 회전이 주어지면, 해당하는 톱니바퀴에서 왼쪽 방향으로 처리를 하는 과정과, 오른쪽으로 처리를 하는 과정을 따로 두어 구현 하였습니다.

 

실제 구현은 아래와 같습니다.

import sys

class wheel:
    def __init__(self,d):
        self.e = d # [d0,d1,d2,d3,d4,d5,d6,d7]
    def rotate(self,direction):
        if direction == 1:
            self.e = [self.e[-1]] + self.e[:-1]
        if direction == -1:
            self.e = self.e[1:] + [self.e[0]]

d1 = list(map(int,list(sys.stdin.readline().rstrip())))
d2 = list(map(int,list(sys.stdin.readline().rstrip())))
d3 = list(map(int,list(sys.stdin.readline().rstrip())))
d4 = list(map(int,list(sys.stdin.readline().rstrip())))

wheel1 = wheel(d1)
wheel2 = wheel(d2)
wheel3 = wheel(d3)
wheel4 = wheel(d4)

wheels = [None, wheel1, wheel2, wheel3, wheel4]

times = int(sys.stdin.readline().rstrip())

for t in range(times):
    n, d = list(map(int, sys.stdin.readline().rstrip().split()))

    original_d = d

    # rotate
    # left(4->1)
    d6 = wheels[n].e[6]

    for i in range(n-1,0,-1):

        if wheels[i].e[2] != d6:
            d6 = wheels[i].e[6]
            wheels[i].rotate(-d)
            d = -d
        else:
            d = 0
            break

    # right(1->4)
    d = original_d
    d2 = wheels[n].e[2]

    for j in range(n+1,5,1):
        if wheels[j].e[6] != d2:
            d2 = wheels[j].e[2]
            wheels[j].rotate(-d)
            d = -d
        else: 
            d = 0
            break


    # self rotate
    d = original_d
    wheels[n].rotate(d)

score = 0
# calculate score
for i in range(1,5):
    if wheels[i].e[0] == 1:
        score += 2**(i-1)
    
print(score)
반응형

'코딩테스트 > Python 문제풀이' 카테고리의 다른 글

[백준] 최소비용 구하기 2  (0) 2022.09.06
[백준] 감시  (0) 2022.07.28
[백준] 경사로  (0) 2022.07.26
[백준] 스타트와 링크  (0) 2022.07.26
[백준] 로봇 청소기  (0) 2022.07.23
    '코딩테스트/Python 문제풀이' 카테고리의 다른 글
    • [백준] 최소비용 구하기 2
    • [백준] 감시
    • [백준] 경사로
    • [백준] 스타트와 링크
    happy318
    happy318

    티스토리툴바