알고리즘

[백준, 자바, 15723번] n단 논법

hminor 2024. 10. 14. 11:40
반응형

풀이

  • 해당 문제는 좀 뭔가 특수했음.
  • 우선 순서가 정해진 알파벳이 아니기에,
  • 배열을 사용하는 것과, 방문 표시를 하기에 고민이 있었음.
  • 물론 만들고자 한다면야 아스키코드로 변환하여 할 수도 있었지만,
  • 그렇게까지 고려한 문제가 아닌거 같아 넘김
  • 그래서 Map을 사용해서 추가
  • 다만 다른 건 쉽게 해결했는데, 계속해서 NoSuchElement 에러가 발생하기에
  • 뭔가하고 찾아보니... StringTokenizer의 두 번째 인자로 넣는 건
  • char 기준으로 구분하다보니 " is "에서 i와 s로 구분하게 되어서
  • i is s를 하면 아무것도 없다고 문구가 나오는 것이었음.
  • 그래서 split을 사용해서 해결했음.

 

import java.io.*;
import java.util.*;
public class _15723 {
    static Deque<String> dq = new ArrayDeque<>();
    static Map<String,List<String>> dic;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        dic = new HashMap<>();

        int N = Integer.parseInt(br.readLine());
        for (int i=0; i<N; i++) {
            String[] XY = br.readLine().split(" is ");
            String x = XY[0];
            String y = XY[1];
            if (!dic.containsKey(x)) dic.put(x,new ArrayList<>(Arrays.asList(y)));
            else dic.get(x).add(y);
        }

        int M = Integer.parseInt(br.readLine());
        for (int i=0; i<M; i++) {
            String[] XY = br.readLine().split(" is ");
            String x = XY[0];
            String y = XY[1];
            dq.add(x);
            bw.write(bfs(y)+"\n");
        }
        bw.flush();
    }

    public static String bfs(String end) {
        while (!dq.isEmpty()) {
            String now = dq.pollFirst();
            if (dic.containsKey(now)) {
                for (String alpha: dic.get(now)) {
                    if (alpha.equals(end)) return "T";
                    dq.add(alpha);
                }
            }
        }
        return "F";
    }
}
//3
//i is s
//s is t
//t is u
//3
//z is b
//c is b
//d is c