Poj-3630(字典树,水题)

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.

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

 

 

题意:

输入:

t组输入

每组一个n,代表下面的电话号码数目

随后n行,每行一个电话号码

输出:

有没有一些号码是另一个号码的前缀,有的话输出NO,没有就输出YES

 

 

思路:

1.先把每个电话号码当作一个字符串构建字典树,每个字符串结尾的节点标记为1,代表这个节点对应的路径有一个单词

2.遍历每个电话号码,看这个号码在字典树的路径上有没有包括一个号码,如果有的话直接输出NO 都没有的话就输出YES

 

输入中没有重复的电话号码

题中n的范围是1e4,但是我开了1e5才过了

代码:

#include<iostream>
#include<string.h>
#include<string>
#include<stdio.h>
#include<cstdlib>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn=1010000;
struct Node
{
    int cnt;
    int net[10];
    Node()
    {
        cnt=0;
        clear();
    }
    void clear()
    {
        cnt=0;
        memset(net,-1,sizeof(net));
    }
} node[maxn];
int top;
void clear_tree(int n)
{
    for(int i=n;~i;--i)
        node[i].clear();
}
int hash_letter(char c)
{
    return c-'0';
}
void insert_node(char *str)
{
    int now=0;
    while(*str)
    {
        if(node[now].net[hash_letter(*str)]==-1)
            node[now].net[hash_letter(*str)]=++top;
        now=node[now].net[hash_letter(*str)];
        ++str;
    }
    node[now].cnt=1;
}
int Solve(char *str)//
{
    //根据str返回前缀结束指针
    int now=0;
    while(*str)//根据当前节点和字符选择该字符对应的节点
    {
        now=node[now].net[hash_letter(*str)];
        ++str;
        if(node[now].cnt&&(*str!='\0'))
        {
            return 0;
        }

    }
    return 1;
}
char words[10100][12];
int main()
{
    int t,n,flag;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        clear_tree(top);
        top=0;
        for(int i=0;i<n;++i)
        {
            scanf("%s",words[i]);
            insert_node(words[i]);
        }
        for(int i=0;i<n;++i)
        {
            flag=Solve(words[i]);
            if(!flag)
                break;
        }
        if(flag)
            printf("YES\n");
        else
            printf("NO\n");
    }
}

 

posted @ 2018-11-01 13:39  _年少有为  阅读(154)  评论(0编辑  收藏  举报