반응형

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

 

5052번: 전화번호 목록

첫째 줄에 테스트 케이스의 개수 t가 주어진다. (1 ≤ t ≤ 50) 각 테스트 케이스의 첫째 줄에는 전화번호의 수 n이 주어진다. (1 ≤ n ≤ 10000) 다음 n개의 줄에는 목록에 포함되어 있는 전화번호가

www.acmicpc.net

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {
    final int GO_MX = 10;

    class Trie {
        Trie[] go;
        boolean output;
        boolean hasChild;

        public Trie() {
            go = new Trie[GO_MX];
            Arrays.fill(go, null);
            output = hasChild = false;
        }

        public void insert(String str, int level) {
            if (level == str.length()) {
                output = true;
                return;
            }
            int next = str.charAt(level) - '0';

            if (go[next] == null) go[next] = new Trie();
            hasChild = true;

            go[next].insert(str, level + 1);
        }

        public boolean consistent() {
            if (this.hasChild && this.output) return false;

            for (int i = 0; i < GO_MX; i++) {
                if (go[i] != null && !go[i].consistent()) return false;
            }

            return true;
        }
    }


    public void solution() throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        int t = Integer.parseInt(br.readLine());

        for (int i = 0; i < t; i++) {
            int n = Integer.parseInt(br.readLine());

            Trie trie = new Trie();
            for (int j = 0; j < n; j++) {
                String str = br.readLine();
                trie.insert(str, 0);
            }


            if (trie.consistent()) {
                sb.append("YES\n");
            } else {
                sb.append("NO\n");
            }
        }
        System.out.println(sb);
    }

    public static void main(String[] args) throws Exception {
        new Main().solution();
    }
}
반응형

+ Recent posts