(NYoj 163)Phone List -- 字典树(水题)

来源:互联网 发布:网络对我们的坏处10条 编辑:程序博客网 时间:2024/06/08 06:52

Phone List
时间限制:1000 ms | 内存限制:65535 KB
难度:4
描述
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:

Emergency 911
Alice 97 625 999
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.

输入
The first line of input gives a single integer, 1 ≤ t ≤ 10, the number of test cases. Each test case starts with n, the number of phone numbers, on a separate line, 1 ≤ n ≤ 100000. Then follows n lines with one unique phone number on each line. A phone number is a sequence of at most ten digits.
输出
For each test case, output “YES” if the list is consistent, or “NO” otherwise.
样例输入
2
3
911
97625999
91125426
5
113
12340
123440
12345
98346
样例输出
NO
YES

分析:
就是一个字典树的建树问题。不懂的可以查看相关字典树的知识点。

AC代码:

#include<cstdio>#include<cstring>#include<iostream> using namespace std;struct node{    node *next[10];    int end;    node(){  //构造函数,方便初始化数据         memset(next,NULL,sizeof(next));        end=0;  //end=0表示一般节点,end=1标志一个电话号的结束     }};node *root;bool insert(char *s){    int i,k,flag;    node *p=root;    for(flag=i=0;s[i];++i){        k=s[i]-'0';        if(p->next[k]==NULL){            p->next[k]=new node();            flag=1;   //标记建立过一个新节点         }         p=p->next[k];        if(p->end) return 0; //碰到结束标志,则返回0     }    p->end=1;  //一个电话号的结束标志     if(!flag) return 0;//字符串插入完毕未出现新建节点的操作,返回0     return 1;}int del(node *p)  //释放字典树空间,否则占用空间太大 {      if(p==NULL) return 0;    for(int i=0;i<10;i++)        if(p->next[i]) del(p->next[i]);    delete p;    return 0;} int main(){    int n,T;    char s[11];    scanf("%d",&T);    while(T--){        bool flag=1;        root=new node();        scanf("%d",&n);        while(n--){            scanf("%s",s);            if(flag) flag=insert(s);//假如出现过混乱情况,则不再进行插入操作         }        del(root);        if(flag) puts("YES");        else puts("NO");    }    return 0;}
0 0
原创粉丝点击