~~Trie树(数据结构)(附题目:AcWing 835. Trie字符串统计)

模板

int son[N][26], cnt[N], idx;
// 0号点既是根节点,又是空节点
// son[][]存储树中每个节点的子节点
// cnt[]存储以每个节点结尾的单词数量

// 插入一个字符串
void insert(char *str)
{
    int p = 0;
    for (int i = 0; str[i]; i ++ )
    {
        int u = str[i] - 'a';
        if (!son[p][u]) son[p][u] = ++ idx;
        p = son[p][u];
    }
    cnt[p] ++ ;
}

// 查询字符串出现的次数
int query(char *str)
{
    int p = 0;
    for (int i = 0; str[i]; i ++ )
    {
        int u = str[i] - 'a';
        if (!son[p][u]) return 0;
        p = son[p][u];
    }
    return cnt[p];
}

例题

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

“I x”向集合中插入一个字符串x;
“Q x”询问一个字符串在集合中出现了多少次。
共有N个操作,输入的字符串总长度不超过 105105,字符串仅包含小写英文字母。

输入格式
第一行包含整数N,表示操作数。

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

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

每个结果占一行。

数据范围
1≤N≤2∗104

输入样例:
5
I abc
Q abc
Q ab
I ab
Q ab
输出样例:
1
0
1

#include<algorithm>
#include<iostream>
#include<string>
using namespace std;
const int N=1e5+10;
int son[N][26],cnt[N];
int idx;
char str[N];
void insert()
{
    int p=0;//根节点
    for(int i=0;str[i];i++)
    {
        int u=str[i]-'a';//把字母转化成数字
        if(!son[p][u]) son[p][u]=++idx;//增加根p的儿子节点
        p=son[p][u];//改变根节点
    }
    cnt[p]++;//记录字符串个数
}
int query()
{
    int p=0;//根节点
    for(int i=0;str[i];i++)
    {
        int u=str[i]-'a';
        if(!son[p][u]) return 0;//无儿子节点,返回0
        p=son[p][u];//更新根节点p
    }
    return cnt[p];//返回字符串个数
}
int main()
{
    int m;
    cin>>m;
    while(m--)
    {
        char op[2];
        cin>>op>>str;
        if(op[0]=='I')
        insert();
        else
        {
            cout<<query()<<endl;
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45884316/article/details/106011512