Inor

[백준] 14891번 톱니바퀴 본문

Algorithm/백준

[백준] 14891번 톱니바퀴

Inor 2017. 11. 13. 14:26

 한 줄로 이어진 톱니바퀴를 회전 시키는 문제입니다. 하나의 톱니바퀴를 회전 시키도록하는 명령어가 들어왔을때, 양 옆의 톱니바퀴에게 영향을 줄 수 있는지를 확인해서 같이 회전 시키도록하는 것이 문제의 핵심입니다.

 4개의 톱니바퀴가 회전해야하는 방향을 담을 수 있는 배열을 선언했습니다. 최초로 회전 명령을 받은 톱니바퀴를 시작으로 배열을 너비 탐색했습니다. 문제의 조건에 따라 너비 탐색으로 탐색된 양 옆의 톱니바퀴의 회전 유무를 판단했습니다. 아래는 문제의 링크와 소스 코드입니다.




- 문제 : https://www.acmicpc.net/problem/14891




- 소스 코드

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Gear {
	int[][] gears;
	int cNum;
	int[][] commands;
	int[] turn;
	boolean[] check;
	int[] next = {-1, 1};
	
	void getData(){
		Scanner sc = new Scanner(System.in);
		String tempStr;
		
		gears = new int[5][8];
		turn = new int[5];
		check = new boolean[5];
		
		for(int i=1;i<gears.length;i++){
			tempStr = sc.nextLine();
			for(int j=0;j<gears[i].length;j++){
				gears[i][j] = tempStr.charAt(j) - '0';
			}
		}
		
		cNum = sc.nextInt();
		commands = new int[cNum][2];
		for(int i=0;i<cNum;i++){
			commands[i][0] = sc.nextInt();
			commands[i][1] = sc.nextInt();
		}
	}
	
	public void turnClockwise(int[] gear){
		int temp = gear[gear.length-1];
		for(int i=gear.length-1;i>0;i--){
			gear[i] = gear[i-1]; 
		}
		gear[0] = temp;
	}
	
	public void turnCounterClockwise(int[] gear){
		int temp = gear[0];
		for(int i=1;i<gear.length;i++){
			gear[i-1] = gear[i];
		}
		gear[gear.length-1] = temp;
	}
	
	public void solution(){
		Queue<Integer> q = new LinkedList<Integer>();
		int nextIdx = -1;
		int nowIdx = -1;
		
		getData();
		
		for(int i=0;i<commands.length;i++){
			q.add(commands[i][0]);
			check[commands[i][0]] = true;
			turn[commands[i][0]] = commands[i][1];
			while(!q.isEmpty()){
				nowIdx = q.poll();
				for(int j=0;j<2;j++){
					nextIdx = nowIdx + next[j];
					if(turn.length <= nextIdx || nextIdx < 1)continue;
					if(check[nextIdx] == true)continue;
					if(nowIdx > nextIdx){
						if(gears[nowIdx][6] != gears[nextIdx][2]){
							turn[nextIdx] = turn[nowIdx]*(-1);
						}
					}else{
						if(gears[nowIdx][2] != gears[nextIdx][6]){
							turn[nextIdx] = turn[nowIdx]*(-1);
						}
					}
					check[nextIdx] = true;
					q.add(nextIdx);
				}
			}
			
			for(int k=1;k<5;k++){
				if(turn[k] == 1)turnClockwise(gears[k]);
				else if(turn[k] == -1)turnCounterClockwise(gears[k]);
				check[k] = false;
				turn[k] = 0;
			}
			
		}

		int ans = 0;
		for(int i=0;i<4;i++){
			ans += gears[i+1][0] * Math.pow(2, i);
		}
		System.out.println(ans);
	}

	public static void main(String[] args) {
		Gear g = new Gear();
		g.solution();
	}

}

'Algorithm > 백준' 카테고리의 다른 글

[백준] 11015번 붕어빵 판매하기  (0) 2017.11.27
[백준] 14888번 연산자 끼워넣기  (0) 2017.11.20
[백준] 5427번 불  (0) 2017.11.06
[백준] 2468번 안전 영역  (0) 2017.11.06
[백준] 14500번 테트로미노  (0) 2017.11.06
Comments