[ 백준 14891번 ] 톱니바퀴

2023. 3. 5. 14:20·Algorithm/문제풀이

1. 문제

 

14891번: 톱니바퀴

첫째 줄에 1번 톱니바퀴의 상태, 둘째 줄에 2번 톱니바퀴의 상태, 셋째 줄에 3번 톱니바퀴의 상태, 넷째 줄에 4번 톱니바퀴의 상태가 주어진다. 상태는 8개의 정수로 이루어져 있고, 12시방향부터

www.acmicpc.net

 

2. 풀이

단순 구현 문제이지만 문제에서 유의해야 할 점은 바로 톱니바퀴가 연쇄적으로 상태가 바뀌는 것이 아니라는 점이다. 이게 무슨 말이냐면 아래 이미지에서 1번 톱니바퀴를 회전시킨 결과에 따라서 2, 3, 4번 톱니바퀴의 회전이 결정되는 것이 아니라는 말이다. 즉, 아래 이미지와 같이 정적인 상태에서 회전 여부가 결정이 되고 최종적으로 한 번에 회전하게 된다는 것이다. 

 

회전에 대한 결과가 다음 회전에 대해 영향을 미치지 않게 구현하기 위해서는 단순 반복문이 아닌 재귀를 통해서 해결해야 한다. 세부 구현은 아래 코드를 참고하자.

 

3. 소스코드

더보기
public class Main {
    static final char N = '0', S = '1';

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        Factory factory = new Factory();
        for (int i = 0; i < 4; i++) {
            factory.setGear(i, br.readLine());
        }

        int K = Integer.parseInt(br.readLine());
        while (K-- > 0) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int idx = Integer.parseInt(st.nextToken()) - 1;
            int dir = Integer.parseInt(st.nextToken());
            factory.rotateGear(idx, idx, dir);
        }

        bw.write(factory.getScore() + "");
        bw.close();
        br.close();
    }

    static class Factory {
        Gear[] gears = new Gear[4];

        void setGear(int idx, String status) {
            this.gears[idx] = new Gear(status);
        }

        int getScore() {
            int tot = 0;
            for (int i = 0; i < 4; i++) {
                tot += gears[i].getGearValue(0) == '0' ? 0 : Math.pow(2, i);
            }
            return tot;
        }

        void rotateGear(int startIdx, int idx, int dir) {
            if (dir == 0) return;

            if (startIdx <= idx && idx < 3) {
                if (gears[idx].getGearValue(2) != gears[idx + 1].getGearValue(6)) {
                    rotateGear(startIdx, idx  + 1, -dir);
                } else {
                    rotateGear(startIdx, idx + 1, 0);
                }
            }

            if (0 < idx && idx <= startIdx) {
                if (gears[idx].getGearValue(6) != gears[idx - 1].getGearValue(2)) {
                    rotateGear(startIdx, idx - 1, -dir);
                } else {
                    rotateGear(startIdx, idx - 1, 0);
                }
            }

            gears[idx].rotate(dir);
        }
    }

    static class Gear {
        char[] status;

        public Gear(String line) {
            this.status = line.toCharArray();
        }

        char getGearValue(int idx) {
            return status[idx];
        }

        void rotate(int dir) {
            if (dir == 0) return;
            if (dir == 1) {
                char temp = status[7];
                for (int i = 7; i >= 1; i--) {
                    status[i] = status[i - 1];
                }
                status[0] = temp;
            } else {
                char temp = status[0];
                for (int i = 0; i <= 6; i++) {
                    status[i] = status[i + 1];
                }
                status[7] = temp;
            }
        }

    }
}

https://github.com/kwanik-kor/BOJ/blob/main/src/simulation/sml_14891_gear.java

 

GitHub - kwanik-kor/BOJ: Baekjoon Online Judge - explanation of solved problems and complete code

Baekjoon Online Judge - explanation of solved problems and complete code - GitHub - kwanik-kor/BOJ: Baekjoon Online Judge - explanation of solved problems and complete code

github.com

 

반응형
저작자표시 비영리 변경금지 (새창열림)

'Algorithm > 문제풀이' 카테고리의 다른 글

[ 백준 15666번 ] N과 M(12)  (1) 2023.03.08
[ 백준 2225번 ] 합분해  (0) 2023.03.06
[ 백준 3190번 ] 뱀  (3) 2023.03.03
[ 백준 10819번 ] 차이를 최대로  (0) 2023.03.03
[ 백준 14499번 ] 주사위 굴리기  (0) 2023.03.03
'Algorithm/문제풀이' 카테고리의 다른 글
  • [ 백준 15666번 ] N과 M(12)
  • [ 백준 2225번 ] 합분해
  • [ 백준 3190번 ] 뱀
  • [ 백준 10819번 ] 차이를 최대로
갈닉
갈닉
중요한 건 엔지니어가 되겠다는 마음. 근데 이제 인문학을 곁들인.
    반응형
  • 갈닉
    KwanIk Devlog
    갈닉
  • 전체
    오늘
    어제
    • 분류 전체보기 (53)
      • Algorithm (41)
        • 알고리즘 개요 (8)
        • 문제풀이 (33)
      • Language (2)
        • Java (1)
        • Kotlin (0)
        • Rust (1)
      • Framework (0)
        • Spring (0)
        • Spring Security (0)
        • Spring Data JPA (0)
      • Computer Science (1)
        • 프로그래밍 언어 (0)
        • 자료구조 (1)
        • 보안 (0)
      • ETC (1)
        • MSA (0)
        • TDD (1)
        • DDD (0)
      • 개발서적 (3)
        • 오브젝트 (3)
      • Life (5)
        • 생각생각 (4)
        • 회고록 (1)
      • Blog in Blog (0)
  • 블로그 메뉴

    • 홈
    • 태그
  • 링크

    • My Github
  • 공지사항

  • 인기 글

  • 태그

    DP
    알고리즘
    backtracking
    greedy
    백준
    boj
    비트마스크
    bitmask
    Algorithm
    오브젝트
    객체지향
    욕심쟁이알고리즘
    백트래킹
    구현
    BruteForce
    시뮬레이션
    java
    BFS
    너비우선탐색
    깊이우선탐색
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
갈닉
[ 백준 14891번 ] 톱니바퀴
상단으로

티스토리툴바