【算法模板】字典树

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43238423/article/details/102485699
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
const int SIZE=1000;
int tot=1;
int trie[SIZE][26];
bool endd[1000000];
char s[10000000];
void insert(char str[])
{
    int len=strlen(str),p=1;
    for(int k=0;k<len;k++)
    {
        int ch=str[k]-'a';
        if(trie[p][ch]==0) trie[p][ch]=++tot;
        p=trie[p][ch];
    }
    endd[p]=true;
}
bool search(char* str)
{
    int len=strlen(str),p=1;
    for(int k=0;k<len;k++)
    {
        p=trie[p][str[k]-'a'];
        if(p==0) return false;
    }
    return endd[p];
}
int main()
{
    int n;

    char op;
    cin>>n;
    while(n--)
    {
        cin>>op>>s;
        if(op=='I') insert(s);
        else cout<<search(s)<<endl;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43238423/article/details/102485699