알고리즘/백준

24955_숫자 이어 붙이기 ****

베리영young 2024. 6. 10. 18:17

사용 알고리즘: bfs

사용 언어 : java

 

package src.alStudy02;

import java.util.*;

public class Main_bj_24955_숫자이어붙이기 {
    static int n, q; //집 개수, 놀이 개수
    static String[] houses; //대문에 쓰인 수
    static ArrayList<Integer>[] al; //인접 리스트
    static int testcase[][];

    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {

        input_24955();

        testcase = new int[n][2];

        for (int test = 0; test < q; test++) {
            int s = sc.nextInt() - 1;
            int e = sc.nextInt() - 1;
            testcase[test][0] = s;
            testcase[test][1] = e;

        }
        for (int test = 0; test < q; test++) {
            bfs_24955(testcase[test][0], testcase[test][1]);
        }
    }

    private static void bfs_24955(int s, int e) {
        Queue<Gate> q = new ArrayDeque();
        StringBuilder sb = new StringBuilder();
        sb.append(houses[s]);

        boolean[] visited = new boolean[n];
        visited[s] = true;
        q.offer(new Gate(s, sb));

        while (!q.isEmpty()) {
            Gate gate = q.poll();

            if(gate.node == e) {
                long ans = Long.parseLong(gate.sb.toString()) % 1000000007;
                System.out.println(ans);
                return;
            }

            for (int nxt : al[gate.node]) {
                if (!visited[nxt]) {
                    visited[nxt] = true;
                    gate.sb.append(houses[nxt]);
                    q.offer(new Gate(nxt, gate.sb));
                }
            }
        }
    }

    private static void input_24955() {

        n = sc.nextInt();
        q = sc.nextInt();

        houses = new String[n];

        for (int i = 0; i < n; i++) {
            houses[i] = sc.next();
        }

        al = new ArrayList[n];
        for (int i = 0; i < n; i++) {
            al[i] = new ArrayList<>();
        }

        for (int i = 0; i < n-1; i++) { //문제에서 간선은 n-1개라고 했음
            int a = sc.nextInt() - 1;
            int b = sc.nextInt() - 1;

            al[a].add(b);
            al[b].add(a);
        }
    }
}

class Gate {
    int node;
    StringBuilder sb;

    public Gate(int node, StringBuilder sb) {
        this.node = node;
        this.sb = sb;
    }
}

 

 

앙? 넘버포맷 오류가 나옴

주어진 예시로 돌리면 잘 나오는데

이유를 잘 모르겠음