[Gold V] 톱니바퀴 - 14891
성능 요약
메모리: 11880 KB, 시간: 80 ms
분류
구현(implementation), 시뮬레이션(simulation)
문제 설명
총 8개의 톱니를 가지고 있는 톱니바퀴 4개가 아래 그림과 같이 일렬로 놓여져 있다. 또, 톱니는 N극 또는 S극 중 하나를 나타내고 있다. 톱니바퀴에는 번호가 매겨져 있는데, 가장 왼쪽 톱니바퀴가 1번, 그 오른쪽은 2번, 그 오른쪽은 3번, 가장 오른쪽 톱니바퀴는 4번이다.
이때, 톱니바퀴를 총 K번 회전시키려고 한다. 톱니바퀴의 회전은 한 칸을 기준으로 한다. 회전은 시계 방향과 반시계 방향이 있고, 아래 그림과 같이 회전한다.
)
톱니바퀴를 회전시키려면, 회전시킬 톱니바퀴와 회전시킬 방향을 결정해야 한다. 톱니바퀴가 회전할 때, 서로 맞닿은 극에 따라서 옆에 있는 톱니바퀴를 회전시킬 수도 있고, 회전시키지 않을 수도 있다. 톱니바퀴 A를 회전할 때, 그 옆에 있는 톱니바퀴 B와 서로 맞닿은 톱니의 극이 다르다면, B는 A가 회전한 방향과 반대방향으로 회전하게 된다. 예를 들어, 아래와 같은 경우를 살펴보자.
두 톱니바퀴의 맞닿은 부분은 초록색 점선으로 묶여있는 부분이다. 여기서, 3번 톱니바퀴를 반시계 방향으로 회전했다면, 4번 톱니바퀴는 시계 방향으로 회전하게 된다. 2번 톱니바퀴는 맞닿은 부분이 S극으로 서로 같기 때문에, 회전하지 않게 되고, 1번 톱니바퀴는 2번이 회전하지 않았기 때문에, 회전하지 않게 된다. 따라서, 아래 그림과 같은 모양을 만들게 된다.
위와 같은 상태에서 1번 톱니바퀴를 시계 방향으로 회전시키면, 2번 톱니바퀴가 반시계 방향으로 회전하게 되고, 2번이 회전하기 때문에, 3번도 동시에 시계 방향으로 회전하게 된다. 4번은 3번이 회전하지만, 맞닿은 극이 같기 때문에 회전하지 않는다. 따라서, 아래와 같은 상태가 된다.
톱니바퀴의 초기 상태와 톱니바퀴를 회전시킨 방법이 주어졌을 때, 최종 톱니바퀴의 상태를 구하는 프로그램을 작성하시오.
입력
첫째 줄에 1번 톱니바퀴의 상태, 둘째 줄에 2번 톱니바퀴의 상태, 셋째 줄에 3번 톱니바퀴의 상태, 넷째 줄에 4번 톱니바퀴의 상태가 주어진다. 상태는 8개의 정수로 이루어져 있고, 12시방향부터 시계방향 순서대로 주어진다. N극은 0, S극은 1로 나타나있다.
다섯째 줄에는 회전 횟수 K(1 ≤ K ≤ 100)가 주어진다. 다음 K개 줄에는 회전시킨 방법이 순서대로 주어진다. 각 방법은 두 개의 정수로 이루어져 있고, 첫 번째 정수는 회전시킨 톱니바퀴의 번호, 두 번째 정수는 방향이다. 방향이 1인 경우는 시계 방향이고, -1인 경우는 반시계 방향이다.
출력
총 K번 회전시킨 이후에 네 톱니바퀴의 점수의 합을 출력한다. 점수란 다음과 같이 계산한다.
- 1번 톱니바퀴의 12시방향이 N극이면 0점, S극이면 1점
- 2번 톱니바퀴의 12시방향이 N극이면 0점, S극이면 2점
- 3번 톱니바퀴의 12시방향이 N극이면 0점, S극이면 4점
- 4번 톱니바퀴의 12시방향이 N극이면 0점, S극이면 8점
풀이
방향을 생각해서 꼼꼼히 구현하면 어렵지 않게 풀 수 있다.
톱니바퀴의 상태를 저장하고, 회전 메서드를 위해 Gear
class를 만들었다.
status에는 String으로 톱니바퀴의 상태를 저장한다.
rotate()
메서드를 통해 1이 입력되면 시계 방향으로, -1이 입력되면 반시계방향으로 회전한다.
static class Gear {
// 맞닿은 구간은 왼쪽 3시(charAt(2)- 오른쪽 9시(charAt(6))
String status;
public Gear(String status) {
this.status = status;
}
public void rotate(int dir) {
if (dir == 1) {
// 시계 방향
this.status = this.status.charAt(7) + this.status.substring(0, 7);
} else if (dir == -1) {
// 반시계 방향
this.status = this.status.substring(1, 8) + this.status.charAt(0);
}
}
@Override
public String toString() {
return "Gear{" +
"status='" + status + '\'' +
'}';
}
}
그리고 K번 번호와 방향이 입력될 때마다 먼저 각 톱니바퀴의 회전 방향을 배열에 저장하고, 하나씩 회전시켰다.
for (int i = 0; i < K; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int num = Integer.parseInt(st.nextToken());
int dir = Integer.parseInt(st.nextToken());
int[] dirs = new int[5];
Arrays.fill(dirs, -2);
fillDir(dirs, num, dir); // 회전 방향 찾기 재귀
for (int j = 1; j <= 4; j++) {
gears[j].rotate(dirs[j]);
}
}
회전 방향을 저장하는 것은 재귀 함수를 활용했다.
현재 위치에서 왼쪽과 오른쪽의 바퀴를 변화시킬 수 있기 때문이다.
static void fillDir(int[] dirs, int num, int dir) {
if (dirs[num] != -2) return;
dirs[num] = dir; // 방향 설정
// 내 방향이 0이라면 아직 방향이 정해지지 않은 내 왼쪽, 오른쪽도 0, *-1해도 0이니까 그냥 한 함수에서
// num+1, num-1에 대해 방향이 있는지 확인, 방향이 아직 정해지지 않았다면 N극 S극 따지기
// 자신의 오른쪽에 있는 기어
if (num + 1 <= 4 && dirs[num + 1] == -2) {
char currDir = gears[num].status.charAt(2); // 왼쪽에 있는 톱니바퀴의 3시 방향
char rightDir = gears[num + 1].status.charAt(6); // 오른쪽에 있는 톱니바퀴의 9시 방향
if (currDir != rightDir) {
fillDir(dirs, num + 1, dir * -1); // 자신과 반대방향으로 채움
} else {
// 방향이 같다면 회전x
fillDir(dirs, num + 1, 0);
}
}
if (num - 1 >= 1 && dirs[num - 1] == -2) {
char currDir = gears[num].status.charAt(6); // 오른쪽에 있는 톱니바퀴의 3시 방향
char leftDir = gears[num - 1].status.charAt(2); // 왼쪽에 있는 톱니바퀴의 9시 방향
if (currDir != leftDir) {
fillDir(dirs, num - 1, dir * -1); // 자신과 반대방향으로 채움
} else {
// 방향이 같다면 회전x
fillDir(dirs, num - 1, 0);
}
}
}
현재 방향의 오른쪽, 왼쪽에 있는 바퀴가 범위 안에 있고 방향이 정해져있지 않을 경우 두 바퀴가 맞닿아있는 부분을 비교해서 방향을 바꿔주었다.
방향이 0인 경우에는 굳이 * -1을 해줄 필요가 없지만 어차피 0을 지정해주는 것이나 0*-1을 지정해주는 것이나 큰 차이가 없기 때문에 따로 처리하지 않았다.
전체 코드
package BOJ.Gold.g5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class BOJ_14891_톱니바퀴 {
static class Gear {
// 맞닿은 구간은 왼쪽 3시(charAt(2)- 오른쪽 9시(charAt(6))
String status;
public Gear(String status) {
this.status = status;
}
public void rotate(int dir) {
if (dir == 1) {
// 시계 방향
this.status = this.status.charAt(7) + this.status.substring(0, 7);
} else if (dir == -1) {
// 반시계 방향
this.status = this.status.substring(1, 8) + this.status.charAt(0);
}
}
@Override
public String toString() {
return "Gear{" +
"status='" + status + '\'' +
'}';
}
}
static Gear[] gears = new Gear[5];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int i = 1; i <= 4; i++)
gears[i] = new Gear(br.readLine());
// 회전에 따라 각 gear의 회전 방향 정하기
int K = Integer.parseInt(br.readLine());
for (int i = 0; i < K; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int num = Integer.parseInt(st.nextToken());
int dir = Integer.parseInt(st.nextToken());
int[] dirs = new int[5];
Arrays.fill(dirs, -2);
fillDir(dirs, num, dir); // 회전 방향 찾기 재귀
for (int j = 1; j <= 4; j++) {
gears[j].rotate(dirs[j]);
}
}
// 점수 계산
int score = 0;
for (int i = 1; i <= 4; i++) {
if (gears[i].status.charAt(0) == '1') {
score += 1 << (i - 1); // 비트연산활용
}
}
System.out.println(score);
}
static void fillDir(int[] dirs, int num, int dir) {
if (dirs[num] != -2) return;
dirs[num] = dir; // 방향 설정
// 내 방향이 0이라면 아직 방향이 정해지지 않은 내 왼쪽, 오른쪽도 0, *-1해도 0이니까 그냥 한 함수에서
// num+1, num-1에 대해 방향이 있는지 확인, 방향이 아직 정해지지 않았다면 N극 S극 따지기
// 자신의 오른쪽에 있는 기어
if (num + 1 <= 4 && dirs[num + 1] == -2) {
char currDir = gears[num].status.charAt(2); // 왼쪽에 있는 톱니바퀴의 3시 방향
char rightDir = gears[num + 1].status.charAt(6); // 오른쪽에 있는 톱니바퀴의 9시 방향
if (currDir != rightDir) {
fillDir(dirs, num + 1, dir * -1); // 자신과 반대방향으로 채움
} else {
// 방향이 같다면 회전x
fillDir(dirs, num + 1, 0);
}
}
if (num - 1 >= 1 && dirs[num - 1] == -2) {
char currDir = gears[num].status.charAt(6); // 오른쪽에 있는 톱니바퀴의 3시 방향
char leftDir = gears[num - 1].status.charAt(2); // 왼쪽에 있는 톱니바퀴의 9시 방향
if (currDir != leftDir) {
fillDir(dirs, num - 1, dir * -1); // 자신과 반대방향으로 채움
} else {
// 방향이 같다면 회전x
fillDir(dirs, num - 1, 0);
}
}
}
}
'문제 풀이 > BOJ' 카테고리의 다른 글
[백준] 2436 - 공약수 (자바 Java) (0) | 2022.12.13 |
---|---|
[백준] 7569 - 토마토 (자바 Java) (0) | 2022.12.12 |
[백준] 1107 - 리모컨 (자바 Java) (0) | 2022.12.04 |
[백준] 5430 - AC (자바 Java) (1) | 2022.12.04 |
[백준] 3190 - 뱀 (자바 Java) (0) | 2022.12.03 |