poj 2001 Shortest Prefixes(trie树)

题目链接:点击打开链接


字典树模板题

在节点里加一个num表示有多少个单词经过这个节点,输出时如果num为1说明只有这个单词经过了这里,就可以break了


模板采用了Trie树——海子这里面的

代码中search函数注释是原模板的本题做了改动


代码:

#include <iostream>
#include <cstdlib>
#include <cstdio>
#define MAX 26
using namespace std;

typedef struct TrieNode                     //Trie结点声明
{
    bool isStr;                            //标记该结点处是否构成单词
    struct TrieNode *next[MAX];         //儿子分支
    int num;
}Trie;

void insert(Trie *root,const char *s)     //将单词s插入到字典树中
{
    if(root==NULL||*s=='\0')
        return;
    int i;
    Trie *p=root;
    while(*s!='\0')
    {
        if(p->next[*s-'a']==NULL)        //如果不存在,则建立结点
        {
            Trie *temp=(Trie *)malloc(sizeof(Trie));
            for(i=0;i<MAX;i++)
            {
                temp->next[i]=NULL;
            }
            temp->num=0;
            temp->isStr=false;
            p->next[*s-'a']=temp;
            p=p->next[*s-'a'];
            p->num++;
        }
        else
        {
            p=p->next[*s-'a'];
            p->num++;
        }
        s++;
    }
    p->isStr=true;                       //单词结束的地方标记此处可以构成一个单词
}

void search(Trie *root,const char *s)  //查找某个单词是否已经存在
{
    Trie *p=root;
    while(p!=NULL)
    {
        p=p->next[*s-'a'];
        printf("%c",*s);
        if(p->num==1){ printf("\n"); break; }
        s++;
        if(*s=='\0'){ printf("\n"); break; }
    }
}

void del(Trie *root)                      //释放整个字典树占的堆区空间
{
    int i;
    for(i=0;i<MAX;i++)
    {
        if(root->next[i]!=NULL)
        {
            del(root->next[i]);
        }
    }
    free(root);
}

int main(){
    char t[1005][25];
    Trie *root= (Trie*)malloc(sizeof(Trie));
    for(int i=0;i<MAX;i++){
        root->next[i]=NULL;
    }
    int len=1;
    while(~scanf("%s",t[len])){
        insert(root,t[len++]);
    }

    for(int i=1;i<len;i++){
        printf("%s ",t[i]);
        search(root,t[i]);
    }

    return 0;
}





你可能感兴趣的:(Trie树)