hdu 1671(字典树判断前缀)
2016-03-21 20:21
429 查看
Phone List
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 16223 Accepted Submission(s): 5456
[align=left]Problem Description[/align]
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.
[align=left]Input[/align]
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.
[align=left]Output[/align]
For each test case, output “YES” if the list is consistent, or “NO” otherwise.
[align=left]Sample Input[/align]
2
3
911
97625999
91125426
5
113
12340
123440
12345
98346
[align=left]Sample Output[/align]
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"); } } }
相关文章推荐
- iOS--归档和解档(Archiver)、(UnArchiver)
- 第一范式
- 利用Apache commons pool2构建池应用
- ListView,ScrollView,RecyclerView被HorizontalScrollView嵌套,加载图片
- java socket报文通信(二)报文的封装
- empty() 和 isset() 的区别
- linux idea14 maven 部署 tomcat. 遇到的问题
- zTree实现清空选中的第一个节点的子节点
- 个人软件开发委托书范本
- 软件工程作业1
- flask 使用错误总结
- 高效求解自然数k次幂和的方法
- mogondb安装常识
- eclipse集成Hadoop 开发环境
- 初入python
- HTTP Headers
- Django修改admin后台管理表单
- ccnet中使用FtpClient.exe程序要注意的要点
- 经典的printk 写法
- 第四章 Controller接口控制器详解(2)