티스토리 뷰

알고리즘

[백준] 9019. DSLR (Java)

melthleeth 2021. 8. 16. 16:05

 

 

9019번: DSLR

네 개의 명령어 D, S, L, R 을 이용하는 간단한 계산기가 있다. 이 계산기에는 레지스터가 하나 있는데, 이 레지스터에는 0 이상 10,000 미만의 십진수를 저장할 수 있다. 각 명령어는 이 레지스터에

www.acmicpc.net

 

풀이

  • BFS로 네 가지 경우 (DSLR)를 전부 탐색한다.
    • int, String을 저장하는 custom class DSLR을 구현했다.
    • 큐에는 (현재 숫자, 지금까지 부른 명령어)를 저장한다.
  • 탐색하다가 현재 숫자가 B가 되면 지금까지의 명령어를 출력한다.
  • visited[]로 숫자 중복 여부를 확인한다.
  • D, S, L, R을 method로 만들어서 사용했다.

 

 

코드

import java.io.*;
import java.util.*;

public class Main {
    static int T, A, B, ans;
    static Queue<DSLR> q;
    static boolean[] visited;

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

        while (T-- > 0) {
            st = new StringTokenizer(br.readLine());
            A = Integer.parseInt(st.nextToken());
            B = Integer.parseInt(st.nextToken());

            bw.write(String.valueOf(solve()));
            bw.newLine();
        }
        br.close();
        bw.close();
    }

    public static String solve() {
        visited = new boolean[10001];
        q = new LinkedList<>();
        q.offer(new DSLR(A, ""));

        while(!q.isEmpty()) {
            int num = q.peek().num;
            String op = q.peek().op;
            q.poll();

            if (num == B) return op;

            int nextNum = D(num);
            if (!visited[nextNum]) {
                visited[nextNum] = true;
                q.offer(new DSLR(nextNum, op + "D"));
            }
            nextNum = S(num);
            if (!visited[nextNum]) {
                visited[nextNum] = true;
                q.offer(new DSLR(nextNum, op + "S"));
            }
            nextNum = L(num);
            if (!visited[nextNum]) {
                visited[nextNum] = true;
                q.offer(new DSLR(nextNum, op + "L"));
            }
            nextNum = R(num);
            if (!visited[nextNum]) {
                visited[nextNum] = true;
                q.offer(new DSLR(nextNum, op + "R"));
            }
        }

        return "";
    }

    public static int D(int num) {
        return (num * 2) % 10000;
    }

    public static int S (int num) {
        return (num + 9999) % 10000;
    }

    public static int L (int num) {
        int temp = num / 1000;
        return (num % 1000) * 10 + temp;
    }
    public static int R (int num) {
        int temp = num % 10;
        return (num / 10) + temp * 1000;
    }

    static class DSLR {
        int num;
        String op;

        public DSLR(int num, String op) {
            this.num = num;
            this.op = op;
        }
    }
}

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함