본문 바로가기

알고리즘 문제풀이/백준

백준(boj) 14891_톱니바퀴 (파이썬, c++)

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

풀이


1, 2, 3, 4번 4개의 톱니바퀴가 있고, 각각 8개의 극이 있다.

n번 톱니 바퀴를 시계 or 반시계 방향으로 돌릴 때, 맞물려 있는 톱니바퀴의 극이 반대 극이면 반대 방향으로 돌려준다.

크기가 4인 배열을 이용해서 시계로 돌아야하면 1을, 반시계로 돌아야하면 -1을, 그대로 이면 0을 표시해서 톱니바퀴를 돌려준다.

python3

from sys import*
input = lambda:stdin.readline().strip()
arr=[list(input())for _ in range(4)]
#12시 방향부터 시계방향 순서로, N극은0, S극은1

def turn(a,b):
   visit[a]=b
   if a-1>=0 and arr[a-1][2] != arr[a][-2] and visit[a-1]==0:
       turn(a-1,-b)
   if a+1<4 and arr[a][2] != arr[a+1][-2] and visit[a+1]==0:
       turn(a+1,-b)
def move(n,b):
   temp=[]
   if b==-1:
       for i in range(8):
           temp.append(arr[n][(i+1)%8])
   else:
       for i in range(8):
           temp.append(arr[n][(i+7)%8])
   for i in range(8):
       arr[n][i]=temp[i]
k=int(input())
for i in range(k):
   a,b = map(int,input().split())  #회전시킨 톱니바퀴 번호, 방향(1시계,-1반시계)
   a-=1
   visit=[0]*4
   turn(a,b)
   for i in range(4):
       if visit[i]:
           move(i,visit[i])
res=0
for i in range(4):
   if arr[i][0]=='1':
       res += 1<<i
print(res)

C++

#include<cstdio>
#include<memory.h>
#include<vector>
using namespace std;
int k, turn[4];
char a[4][8];
void solve(int n, int d){
   turn[n] = d;
   if(n-1 >= 0 && !turn[n-1] && (a[n-1][2] != a[n][6]))
       solve(n-1, -d);
   if(n+1 < 4 && !turn[n+1] && (a[n][2] != a[n+1][6]))
       solve(n+1, -d);
}
void move(){
   for(int i=0; i<4; i++){
       vector<char> v;
       if(!turn[i]) continue;
       if(turn[i] == 1){    //시계
           for(int j=0; j<8; j++){
               v.push_back(a[i][(j+7)%8]);
          }
      }
       else if(turn[i] == -1){        //반시계
           for(int j=0; j<8; j++){
               v.push_back(a[i][(j+1)%8]);
          }
      }
       for(int j=0; j<8; j++)
           a[i][j] = v[j];
  }
}
int main(){
   for(int i=0; i<4; i++)
       scanf("%s", &a[i]);
   scanf("%d", &k);
   for(int i=0; i<k; i++){
       int n, d;
       scanf("%d %d", &n, &d);
       memset(turn, 0, sizeof(turn));
       solve(n-1, d);
       move();
  }
   int res=0;
   for(int i=0; i<4; i++)
       if(a[i][0] == '1') res += (1<<i);
   printf("%d", res);
   return 0;
}

고찰


.