HDOJ-1671-字典树
2015-08-17 08:55
232 查看
Phone List
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 14623 Accepted Submission(s): 4932
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.
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
大致题意:给定一些字符串,判断是否有两个字符串的前缀相同。前缀不包括自身,如样例 911 和 91125426 不算,而 12340和 123440则符合,很明显使用字典树解答。
#include<iostream> #include<cstdio> #include<cstring> using namespace std; #define MAX 10 struct node{ int key; node *next[MAX]; node(){ key=0; for(int i=0;i<MAX;i++) next[i]=NULL; } }; node *root; void tireInsert(char *str){ node*p=root,*q; for(int i=0;str[i];i++){ int id=str[i]-'0'; if(!p->next[id]) p->next[id]=new node(); p=p->next[id]; } p->key=1; } void dell(node*p) { if(p){ for(int i=0;i<MAX;i++) if(p->next[i]){ dell(p->next[i]); delete p->next[i]; } } } int tireFind(char *str) { node *p=root; int len=strlen(str); for(int i=0;str[i];i++){ int id=str[i]-'0'; p=p->next[id]; if(!p)return 1; if(p->key==1&&i<len-1)return 0; } return 1; } int main() { int N,T,i; char str[10005][11]; scanf("%d",&T); while(T--) { scanf("%d",&N); root=new node(); for(i=0;i<N;i++){ scanf("%s",str[i]); tireInsert(str[i]); } for(i=0;i<N;i++) if(!tireFind(str[i])) break; printf(i<N?"NO\n":"YES\n"); dell(root);\\及时释放内存否则会超内存 } }
相关文章推荐
- TTL与RS-485电平转换芯片MAX485/MAX3485
- MAX13487E, MAX13488E半双工RS-485/RS-422收发器,带有自动选向控制
- mysql数据库主从同步过程详述
- 三种继承方式的区别
- C++强制转换类型
- 游戏展已经走向了它的终点,除非……
- vim常用快捷键
- 【bzoj3105】【新Nim游戏】【bzoj2460】【元素】
- 大学就知道认真写博客-但现实总是偏离轨迹
- Critical thinking and Thoughtful writing
- activiti集成drools实验
- HDInsight - 1,简介
- 实现ModelDriver接口的功能
- 【Ajax技术】利用XHR接受与处理XML数据
- IOS开发类似于微博个人中心的头像可以拖动lei
- jQuery中的datatable 插件新增一行
- java虚拟机内存管理介绍
- Android下运行时动态链接dlopen()和dlsym()的实现
- 软件汉化
- tcp ip协议笔记(4)——arp