Trie树-模板

Trie树是一种高效存储和查找字符串的数据结构。

例题:

维护一个字符串集合,支持两种操作:

  1. “I x”向集合中插入一个字符串x;
  2. “Q x”询问一个字符串在集合中出现了多少次。

共有N个操作,输入的字符串总长度不超过 105105,字符串仅包含小写英文字母。

输入格式

第一行包含整数N,表示操作数。

接下来N行,每行包含一个操作指令,指令为”I x”或”Q x”中的一种。

输出格式

对于每个询问指令”Q x”,都要输出一个整数作为结果,表示x在集合中出现的次数。

每个结果占一行。

数据范围

1≤N≤2∗1041≤N≤2∗104

输入样例:

5
I abc
Q abc
Q ab
I ab
Q ab

Trie树的数据结构如图所示: 

                                   

特点:

下标是零的点即是根节点,又是空节点。

插入和查找的方式相同。需要将小写字母映射成0-25的下标。

代码:

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;
const int N=100010;

int son[N][26],cnt[N],idx;
char str[N];

void insert(char tr[])
{
    int p=0;
    for(int i=0;tr[i];i++)
    {
        int u=tr[i]-'a';
        if(!son[p][u]) son[p][u]=++idx;
        p=son[p][u];
    }
    cnt[p]++;
    
}

int query(char tr[])
{
    int p=0;
    for(int i=0;tr[i];i++)
    {
        int u=tr[i]-'a';
        if(!son[p][u]) return 0;
        p=son[p][u];
    }
    return cnt[p];
    
}
int main()
{
    int n;
    cin>>n;
    while(n--)
    {
        char op[2];
        
        cin>>op>>str;
        if(*op=='I') insert(str);
        else 
        printf("%d\n",query(str));
        
    }
    return 0;
}
发布了22 篇原创文章 · 获赞 7 · 访问量 424

猜你喜欢

转载自blog.csdn.net/qq_40905284/article/details/104306665
今日推荐