hdu 1671 Trie树简单应用

来源:互联网 发布:太原市知达常青藤学校 编辑:程序博客网 时间:2024/05/21 17:02

                                                      Phone List

                                       Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)


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
2391197625999911254265113123401234401234598346
 

Sample Output
NOYES
 

链接:http://acm.hdu.edu.cn/showproblem.php?pid=1671

题目大意:就是判断输入的电话号码中是否有号码是其他号码的前缀,很显然要用到字典树。

v,用来表示是否有一个串在该节点结束,这主要是针对前面的串中出现过当前串的前缀;

另一个是f,用来标志当前当一个串结束时,它是否存在下一个节点,主要针对当前串是之前出现过的串的前缀

注:每一个case之后,要释放空间,不然内存使用过大了

代码:

#include <iostream>#include <stdio.h>#include <stdlib.h>#include <string.h>using namespace std;struct Trie{    int f;    int v;    Trie *next[10];}*root;int flag;void insert(char *str){    Trie *p,*t;    p=root;    int len=strlen(str);    for(int i=0;i<len;i++)    {        int id=str[i]-'0';        if(p->next[id]!=NULL)        {            p->f=1;            p=p->next[id];            if(p->v==-1)            flag=1;        }        else        {            t=new Trie;            for(int i=0;i<10;i++)            {                t->next[i]=NULL;            }            t->v=0;            t->f=0;            p->f=1;            p->next[id]=t;            p=t;        }    }    p->v=-1;    if(p->f)    flag=1;}int del(Trie *T){    for(int i=0;i<10;i++)    {        if(T->next[i]!=NULL)        del(T->next[i]);    }    free(T);    return 0;}int main(){    int t;    scanf("%d",&t);    char str[15];    while(t--)    {        flag=0;        root=new Trie;        for(int i=0;i<10;i++)        {            root->next[i]=NULL;        }        root->f=0;        root->v=0;        int n;        scanf("%d",&n);        getchar();        while(n--)        {            gets(str);            if(flag)            continue;            insert(str);        }        if(!flag)        printf("YES\n");        else        printf("NO\n");        del(root);    }    return 0;}



 
0 0
原创粉丝点击