Phone List

时间限制: 1000 ms  |  内存限制:65535 KB
难度: 4
 
<dl class="problem&#45;display"> <dt> 描述 </dt> <dd>

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.

</dd> </dl>
 
<dl class="others"> <dt> 输入 </dt> <dd> 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. </dd> <dt> 输出 </dt> <dd> For each test case, output "YES" if the list is consistent, or "NO" otherwise. </dd> <dt> 样例输入 </dt> <dd>
2
3
911
97625999
91125426
5
113
12340
123440
12345
98346
</dd> <dt> 样例输出 </dt> <dd>
NO
YES
解题思路:刚开始直接看测试数据差点误解,以为是按顺序存储的就输出yes呢。。。。仔细翻译才明白。
  
字典树,就是按照一定的顺序来构造一棵树,对于很多字符串来说,有很多重复的前缀,那么相同的前缀就不用都存储一遍了,用一个相同前缀来存储就可以。
  此题判断是否有前缀有两种情况(每次都是按位存),① 如果挨着往里存储,当此时的字符串a都存储完的时候还没有建立新的节点,说明在此之前已经有一个字符串b了,所以a是b的前缀。
  ② 当这个a字符串还没有存储完成就碰到endd=1,说明之前有一个字符串b已经结束了,b是这个a的前缀。
代码:
</dd> </dl>
#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

typedef struct tree{
    int endd;
    tree *next[10];
    tree(){
        endd=0;
        memset(next,NULL,sizeof(next));
    }
};
tree *root;

int inser(char a[]){
    int flag=0;
    tree *p=root;
    int k;
    int len=strlen(a);
    for(int i=0;i<len;i++){
        k=a[i]-'0';
        if(p->next[k]==NULL){
            p->next[k]=new tree;
            flag=1;
        }
        p=p->next[k];
        if(p->endd){
            return 0;
        }
    }
    p->endd=1;
    if(!flag){
        return 0;
    }
    return 1;
}

int main()
{
    int t;
    char a[10];
    scanf("%d",&t);
    while(t--){
        int n;
        int flag=1;
        root=new tree();
        scanf("%d",&n);
        while(n--){
            scanf("%s",a);
            if(flag){
                flag=inser(a);
            }
        }
        if(!flag){
            printf("NO\n");
        }else{
            printf("YES\n");
        }
    }
    return 0;
}