Develope/알고리즘

[백준 14891] 톱니바퀴 - java

고로이 2018. 2. 12. 17:37
반응형

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

시간 제한메모리 제한제출정답맞은 사람정답 비율
2 초512 MB116445036343.735%

문제

총 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점

















ㅁㄴㅇ







아 문제 개어렵다....젠장..




package beak.gear_14891;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* Created by eunbi on 2018-02-17.
* 서로 맞닿은 톱니의 극이 다르다면, B는 A가 회전한 방향과 반대방향으로 회전하게 된다.
*/

public class gear_EB {
public static StringBuilder sb = new StringBuilder();
public static java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
public static java.util.Scanner sc = new java.util.Scanner(System.in);
public static int K;
public static int N;
public static int M;

public static List<Gear> gearList = new ArrayList<Gear>();

public static void main(String[] args) throws Exception {
solve();
}

public static void solve() throws Exception {
int i = 0;
for (; i < 4; i++) {
Gear gear = new Gear(br.readLine());
gearList.add(gear);
}
K = Integer.parseInt(br.readLine());

//printGear();
for (int j = 1; j <= K; j++) {
// n 번호, M은 방향
String[] line = br.readLine().split(" ");
N = Integer.parseInt(line[0]);
M = Integer.parseInt(line[1]);
gearing(N-1, M);
// printGear();

}
int sum=0;
int k=0;
for(int j=1; j<9; j*=2){
if(gearList.get(k).magList[gearList.get(k).upIndex] == 1){
sum += j;
}
k++;
}
System.out.println(sum);
}

public static void gearing(int gearNum, int clock) {
// System.out.println("GearNum : "+gearNum +" / clock : "+clock);
Gear currentGear = gearList.get(gearNum);


rolling(gearNum + 1, 1, -1*clock);
rolling(gearNum - 1, -1, -1*clock);
currentGear.upIndex = (8 + currentGear.upIndex - clock) % 8;
}

//3,1 서로 맞닿은 톱니의 극이 다르다면, B는 A가 회전한 방향과 반대방향으로 회전하게 된다.
public static void rolling(int gearNum, int direction, int clock) {
if (gearNum < 0 || gearNum >= 4) return;

Gear currentGear = gearList.get(gearNum);
Gear beforeGear = gearList.get(gearNum - direction);

//오른쪽방향
if (direction == 1) {
// 톱니의 극이 다르면
if (beforeGear.magList[beforeGear.getRightIndex()] != currentGear.magList[currentGear.getLeftIndex()]) {
// 재귀함수 호출
rolling(gearNum + 1, direction, -1*clock);

//인덱스 변경(돌리기)
currentGear.upIndex = (8 + currentGear.upIndex - clock) % 8;
}
} else {
//왼쪽방향
if (beforeGear.magList[beforeGear.getLeftIndex()] != currentGear.magList[currentGear.getRightIndex()]) {
rolling(gearNum - 1, direction, -1*clock);
currentGear.upIndex = (8 + currentGear.upIndex - clock) % 8;
}
}
// rolling(gearNum + direction, direction, clock);
}
public static class Gear {
int[] magList = new int[8];
int upIndex = 0;

public Gear(String line) {
int i = 0;
for (char c : line.toCharArray()) {
magList[i] = (int) c - 48;
i++;
}
}
public int getRightIndex() {
return (upIndex + 2) % 8;
}
public int getLeftIndex() {
return (upIndex + 6) % 8;
}
@Override
public String toString() {
return "Gear{" +
"magList=" + Arrays.toString(magList) +
'}';
}
}
public static void printGear() {
String[] output = new String[6];
for (int i = 0; i < 6; i++) {
output[i] = "";
}
for (int i = 0; i < 4; i++) {
int[] magList = gearList.get(i).magList;
int upIndex = gearList.get(i).upIndex;

output[0] = output[0] + "*" + i + "번 / "+upIndex+" \t";

output[1] = output[1] + " " + magList[(0 + upIndex) % 8] + " \t";
output[2] = output[2] + " " + magList[(7 + upIndex) % 8] + " " + magList[(1 + upIndex) % 8] + " \t";
output[3] = output[3] + magList[(6 + upIndex) % 8] + " " + magList[(2 + upIndex) % 8] + "\t";
output[4] = output[4] + " " + magList[(5 + upIndex) % 8] + " " + magList[(3 + upIndex) % 8] + " \t";
output[5] = output[5] + " " + magList[(4 + upIndex) % 8] + " \t";
}

for (int i = 0; i < 6; i++) {
System.out.println(output[i]);
}
System.out.println();
}
}


쫄앗던 것과는 달리 그렇게 어렵지는 않았다


PrintGear 함수를 쓰면 이쁘게 출력되니 누군가 이글을 본다면 잘쓰길 바란다


GearNum : 3 / clock : 1

*0번 / 0 *1번 / 7 *2번 / 7 *3번 / 7

    1        1        1        1   

  1   1    1   1    1   1    1   1 

1       1 1       1 1       1 1       1

  1   1    1   1    1   1    1   1 

    1        1        1        1   



public static class Gear {
int[] magList = new int[8];
int upIndex = 0;

public Gear(String line) {
int i = 0;
for (char c : line.toCharArray()) {
magList[i] = (int) c - 48;
i++;
}

}
public int getRightIndex() { return (upIndex + 2) % 8; }
public int getLeftIndex() { return (upIndex + 6) % 8; }
@Override
public String toString() {
return "Gear{" +
"magList=" + Arrays.toString(magList) +
'}';
}
}

일단 기어 클래스는 다음과 같다


* 8면에 대한 S/N극 리스트.

* upIndex : 현재 북쪽에 위치한 자석의 인덱스. 초기값은 0이다

- get index : 현재 기어에서 동/서 방향의 자석을 알려주는 함수



회전을 하게 되면 그에따라 upIndex 가 바뀌는 구조



public static void solve() throws Exception {
/**
* 1. Gear 입력 및 초기화
*/
int i = 0;
for (; i < 4; i++) {
Gear gear = new Gear(br.readLine());
gearList.add(gear);
}
K = Integer.parseInt(br.readLine());

/**
* 2. Input 값에 맞는 기어 조작
*/
for (int j = 1; j <= K; j++) {
// n 번호, M은 방향
String[] line = br.readLine().split(" ");
N = Integer.parseInt(line[0]);
M = Integer.parseInt(line[1]);
gearing(N-1, M);
// printGear();

}

/**
* 3. 회전을 마치고 북쪽의 극을 찾아 더함
*/
int sum=0;
int k=0;
for(int j=1; j<9; j*=2){
if(gearList.get(k).magList[gearList.get(k).upIndex] == 1){
sum += j;
}
k++;
}
System.out.println(sum);
}

비즈니스 로직 부분이다


public static void gearing(int gearNum, int clock) {
// System.out.println("GearNum : "+gearNum +" / clock : "+clock);
Gear currentGear = gearList.get(gearNum);

rolling(gearNum + 1, 1, -1*clock);
rolling(gearNum - 1, -1, -1*clock);
currentGear.upIndex = (8 + currentGear.upIndex - clock) % 8;
}


1. 현재 기어를 중심으로 오른쪽, 왼쪽의 rolling 함수를 호줄한다. (돌릴 기어, 돌리는 방향, 회전방향)

2. 회전한 방향에 따라 현재기어의 upIndex 를 수정한다.



//3,1 서로 맞닿은 톱니의 극이 다르다면, B는 A가 회전한 방향과 반대방향으로 회전하게 된다.
public static void rolling(int gearNum, int direction, int clock) {
if (gearNum < 0 || gearNum >= 4) return;

Gear currentGear = gearList.get(gearNum);
Gear beforeGear = gearList.get(gearNum - direction);

//오른쪽방향
if (direction == 1) {
// 톱니의 극이 다르면
if (beforeGear.magList[beforeGear.getRightIndex()] != currentGear.magList[currentGear.getLeftIndex()]) {
// 재귀함수 호출
rolling(gearNum + 1, direction, -1*clock);

//인덱스 변경(돌리기)
currentGear.upIndex = (8 + currentGear.upIndex - clock) % 8;
}
} else {
//왼쪽방향
if (beforeGear.magList[beforeGear.getLeftIndex()] != currentGear.magList[currentGear.getRightIndex()]) {
rolling(gearNum - 1, direction, -1*clock);
currentGear.upIndex = (8 + currentGear.upIndex - clock) % 8;
}
}
// rolling(gearNum + direction, direction, clock);
}




반응형

'Develope > 알고리즘' 카테고리의 다른 글

[알고스팟] BOARDCOVER - java  (0) 2018.02.12
[알고스팟] PICNIC - java  (4) 2018.02.06
[백준 - 1158] 조세퍼스 문제  (0) 2018.01.04
[백준 - 2140] 지뢰찾기  (0) 2017.12.19
[알고스팟] XHAENEUNG  (5) 2017.12.11