Coding Test/baekjoon

[백준 14891] 톱니바퀴 - python (solved.ac - 골드 5)

조용장 2022. 5. 1. 21:30

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

 

14891번: 톱니바퀴

첫째 줄에 1번 톱니바퀴의 상태, 둘째 줄에 2번 톱니바퀴의 상태, 셋째 줄에 3번 톱니바퀴의 상태, 넷째 줄에 4번 톱니바퀴의 상태가 주어진다. 상태는 8개의 정수로 이루어져 있고, 12시방향부터

www.acmicpc.net

풀이

문제를 보았을때 알수있는 힌트

문제는 길지만 이해하면 쉽게 풀 수 있는 문제

톱니바퀴는 8개로 되어있다. [1,0,1,1,1,1,1,0] 로 되어있다고 가정하자

총 4개의 톱니 바퀴가 존재하고 반시계방향(-1)으로 움직일때는 맨앞에 수를 맨뒤로 보내고, 시계방향(1)으로 움직이면 맨뒤를 맨 앞으로 보내주면 된다.

리스트에서 pop.append, insert를 활용하면 충분히 움직일수있다.

재귀 함수를 통해서 맨 나중에 움직일 톱니바퀴를 먼저 움직이게 하고나서 처음꺼는 맨 마지막에 움직이게 하면 풀린다.

 

import sys

n_list = []

def rotation_l(gear,rotation):
    if gear!=0:
        if n_list[gear-1][2]!=n_list[gear][-2]:
            rotation_l(gear-1,-rotation)
            if -rotation==-1:
                v= n_list[gear-1].pop(0)
                n_list[gear-1].append(v)
            else:
                v= n_list[gear-1].pop(-1)
                n_list[gear-1].insert(0,v)

def rotation_r(gear,rotation):
    if gear!=3:
        if n_list[gear][2]!=n_list[gear+1][-2]:
            rotation_r(gear+1,-rotation)
            if -rotation==-1:
                v= n_list[gear+1].pop(0)
                n_list[gear+1].append(v)
            else:
                v= n_list[gear+1].pop(-1)
                n_list[gear+1].insert(0,v)
                         
input = sys.stdin.readline

for i in range(4):
    temp= list(map(int,(input().strip())))
    n_list.append(temp)

n= int(input())
result=0
for _ in range(n):
    temp = list(map(int,input().split()))
    gear = temp[0]-1
    rotation=temp[1]
    rotation_l(gear,rotation)
    rotation_r(gear,rotation)
    if rotation==-1:
        v= n_list[gear].pop(0)
        n_list[gear].append(v)
    else:
        v= n_list[gear].pop(-1)
        n_list[gear].insert(0,v)

result=n_list[0][0]+n_list[1][0]*2+n_list[2][0]*4+n_list[3][0]*8
print(result)

https://github.com/dydwkd486/coding_test/blob/main/baekjoon/baekjoon14891.py

 

GitHub - dydwkd486/coding_test: 코딩테스트 공부한 내용 정리

코딩테스트 공부한 내용 정리. Contribute to dydwkd486/coding_test development by creating an account on GitHub.

github.com