• 字典树基础模板


    /*
    字典树
    操作:
    1.插入
    3.查找
    */
    #include<cstdio>
    #include<iostream>
    #include<string.h>
    using namespace std;
    const int MAXN=10010;//单词的个数
    const int ALPH=26;//字母表个数
    typedef struct TireNode{
        TireNode* next[ALPH];
        int count;//表示该节点对应单词的个数
        TireNode()
        {
            count=0;
            for(int i=0;i<ALPH;++i)
                next[i]=NULL;
        };
    } Node;
    Node node[MAXN];
    int top=0;
    Node* root;
    Node* CreatNode()
    {
        Node* np=&node[top++];
        return np;
    }
    void InsertNode(Node* root,char *s)//字符串的根  字符串
    {
        int len=strlen(s);
        Node *newp;
        newp=root;
        for(int i=0;i<len;++i)
        {
            if(newp->next[s[i]-'a']==NULL)
            {
                newp->next[s[i]-'a']=CreatNode();
            }
            newp=newp->next[s[i]-'a'];
        }
        newp->count+=1;
    }
    Node* searchNode(Node* root,char* s)//返回节点对应的地址
    {
        int len=strlen(s);
        Node* newp;
        newp=root;
        for(int i=0;i<len;++i)
        {
            newp=newp->next[s[i]-'a'];
            if(!newp)
                return NULL;
        }
        return newp;
    }
    int main()
    {
        top=0;
        root=&node[top++];
        int m;
        char s[30];
        scanf("%d",&m);
        while(m--)
        {
            scanf("%s",s);
            InsertNode(root,s);
        }
        int n;
        scanf("%d",&n);
        while(n--)
        {
            scanf("%s",s);
            Node* midp;
            midp=searchNode(root,s);
            if(midp==NULL)
                cout<<0<<endl;
            else
             cout<<midp->count<<endl;
        }
    }
    

    每个节点有有一个指针数组,指向字母对应的下一个节点。若对应节点不存在,则p=null。

  • 相关阅读:
    CSS 中 Position relative 和 absolute区别
    感受到LDT的好处
    Map数据结构
    break和continue
    vue的ref属性
    css小样式
    搭建vue开发环境
    setTimeout和clearTimeout
    垂直居中
    vertical-align 属性
  • 原文地址:https://www.cnblogs.com/dchnzlh/p/9780056.html
Copyright © 2020-2023  润新知