Algorithm/problem
백준 5052번 : 전화번호 목록 - 트라이, JAVA
DingCoDing
2022. 12. 30. 18:57
반응형
https://www.acmicpc.net/problem/5052
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();
}
}
반응형