Phone List
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 16223 Accepted Submission(s): 5456
Problem Description
Given
a list of phone numbers, determine if it is consistent in the sense
that no number is the prefix of another. Let’s say the phone catalogue
listed these numbers:
1. Emergency 911
2. Alice 97 625 999
3. Bob 91 12 54 26
In this case, it’s not possible to call Bob, because the central would direct your call to the emergency line as soon as you had dialled the first three digits of Bob’s phone number. So this list would not be consistent.
1. Emergency 911
2. Alice 97 625 999
3. Bob 91 12 54 26
In this case, it’s not possible to call Bob, because the central would direct your call to the emergency line as soon as you had dialled the first three digits of Bob’s phone number. So this list would not be consistent.
Input
The
first line of input gives a single integer, 1 <= t <= 40, the
number of test cases. Each test case starts with n, the number of phone
numbers, on a separate line, 1 <= n <= 10000. Then follows n
lines with one unique phone number on each line. A phone number is a
sequence of at most ten digits.
Output
For each test case, output “YES” if the list is consistent, or “NO” otherwise.
Sample Input
2
3
911
97625999
91125426
5
113
12340
123440
12345
98346
Sample Output
NO
YES
只有一个地方值得注意,就是我代码中标记的那个地方
package 字典树; import java.util.Scanner; class Trie { private Node root; public Trie() { root = new Node(); } public boolean insert(String str) { Node t = root; for (int i = 0; i < str.length(); i++) { if (t.nodes[str.charAt(i) - '0'] == null) { Node node = new Node(); t.nodes[str.charAt(i) - '0'] = node; } t = t.nodes[str.charAt(i) - '0']; if (t.isNumber) { //如果相同前缀出现过了 return false; } } t.isNumber = true; //写了这段就AC了,判断一下他的子节点是否存在,存在就证明它绝对是某个的前缀 ,比如说输入 91111 911 如果不加此判断 91111的标记是在最后一个 // ‘1’,再次输入 911 就判断不到了 。。 WA了好多次 for(int i=0;i<=9;i++){ if(t.nodes[i]!=null) return false; } return true; } class Node { boolean isNumber; Node[] nodes; public Node() { isNumber = false; nodes = new Node[11]; } } } public class hdu_1671 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int tcase = sc.nextInt(); while (tcase-- > 0) { boolean flag = true; Trie tree = new Trie(); int n = sc.nextInt(); for (int i = 0; i < n; i++) { String str = sc.next(); if (flag) { flag = tree.insert(str); } } if (!flag) System.out.println("NO"); else System.out.println("YES"); } } }