【算法模板】字典樹

#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;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章