HDU 1671——Trie树应用

看不懂可以先看看讲解http://blog.csdn.net/chuck001002004/article/details/50421065

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

题意:给定一些字符串,判断是否存在一些字符串是其他字符串的前缀。如:第一组数据 911 是最后一个 91125426 的前缀,故拨打时容易直接播出 911 输出“NO”,反之,输出“YES”。

分析:每读入一个电话号码,判断其第1到n-1位是否有相同的其他号码即可。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
int T,n;
char num[10005][15],phone[15];
bool flag;
typedef struct TrieNode
{
    bool end;        //标记电话号码结束
    TrieNode *next[10];//数字1到9每个设一个分节点
}Trie;
Trie *root;
void init()  //初始化函数
{
    root=(Trie*)malloc(sizeof(Trie));
    root->end=false;
    for(int i=0;i<10;i++)
        root->next[i]=NULL;
    flag=true;
}
void Insert(char *num)
{
    if(root==NULL&&*num=='\0')
        return ;
    Trie *p=root;
    while(*num!='\0')
    {
        if(p->next[*num-'0']==NULL)
        {
            Trie *t=(Trie*)malloc(sizeof(Trie));
            for(int i=0;i<10;i++)
                t->next[i]=NULL;
            t->end=false;
            p->next[*num-'0']=t;
            p=p->next[*num-'0'];
        }
        else
        {
            p=p->next[*num-'0'];
        }
        num++;
    }
    p->end=true;
}
int Search(char *phone)
{
    Trie *p=root;
    for(int i=0;phone[i]!='\0';i++)
    {
        if(p==NULL||p->next[phone[i]-'0']==NULL)
            return false;  //出现不对应的情况就返回false
        else
            p=p->next[phone[i]-'0'];
    }
    return p->end; 
}
void Del(Trie *root)
{
    for(int i=0;i<10;i++)
    {
        if(root->next[i]!=NULL)
            Del(root->next[i]);
    }
    free(root);
}

int main()
{
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        init();
        for(int i=0;i




你可能感兴趣的:(经典题目)