Problem Solving/구현

BOJ14891 톱니바퀴

윤재에요 2024. 4. 12. 20:01

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

 

14891번: 톱니바퀴

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

www.acmicpc.net

package test_sds;
import java.io.*;
import java.util.*;

public class topni {
	static int[][] wheel= new int[4][8];
	static int n;
	public static void main(String[] args) throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		for(int i=0;i<4; i++) {
			String[] temp = br.readLine().split("");
			for(int j=0; j<8;j++) {
				wheel[i][j]=Integer.parseInt(temp[j]);
			}
		}
		
		n= Integer.parseInt(br.readLine());
		
		for(int i=0; i<n;i++) {
			String[] temp = br.readLine().split(" ");
			int selectedWheel = Integer.parseInt(temp[0])-1;
			int direction = Integer.parseInt(temp[1]);
			 
			//선택 톱니 기준 왼쪽 방향 
			for(int j=selectedWheel; j>=0;j--) {
				// j-1인덱스 체크후 마지막톱니면 continue
				
				if(j-1>=0) {
					// 인덱스 존재하면 wheel[j-1][2]와 wheel[j][6] 같은지 체크
					if(wheel[j-1][2]==wheel[j][6]) {
						// 같다면 turng하고 break;
						// 밑에서초기 톱니를 한번 떠 써야하니 첫번째 톱니는 이동 ㄴㄴ 
						if(j!=selectedWheel) {
							turn(j,direction);
						}
						break;
					}else {
						if(j!=selectedWheel) {
							turn(j,direction);
						}
						direction*=-1;
					}
					//다르다면 turn하고 didection 반대로 변경, 반복문 진;					 
 

				}else {
					//마지막 톱니여서 혼자만 교환
					if(j!=selectedWheel) {
						turn(j,direction);
					}
				}
				
			}

			// 다시 첫 톱니이동 방향으로 수정  
			direction = Integer.parseInt(temp[1]);
			
			//선택 톱니 기준 오른쪽 방향 
			for(int j=selectedWheel; j<4;j++) {
				// j+1인덱스 체크후 마지막톱니면 continue
				
				if(j+1<4) {
					// 인덱스 존재하면 wheel[j-1][2]와 wheel[j][6] 같은지 체크
					if(wheel[j][2]==wheel[j+1][6]) {
						// 같다면 turng하고 break;					
						turn(j,direction);
						break;
					}else {
						turn(j,direction);
						direction*=-1;
					}
					//다르다면 turn하고 didection 반대로 변경, 반복문 진;					 
 

				}else {
					//마지막 톱니여서 혼자만 교
					turn(j,direction);
				}
				
			}			
			
			
	
			
		}
		

		
		
		int ans = 0;
		for(int i=0; i<4; i++) {
			ans+=Math.pow(2,i)*wheel[i][0];
		}
		System.out.println(ans);
		
		
		
	}
	
	public static void turn(int wheel_idx, int direction) {
		if(direction==1) {
			int temp = wheel[wheel_idx][7];
			for(int i=7;i>0;i--) {
				wheel[wheel_idx][i] = wheel[wheel_idx][i-1];
			}
			wheel[wheel_idx][0]= temp;
		}
		
		if(direction==-1) {
			int temp = wheel[wheel_idx][0];
			for(int i=0;i<7;i++) {
				wheel[wheel_idx][i] = wheel[wheel_idx][i+1];
			}
			wheel[wheel_idx][7]= temp;
		}
		
		
	}
}