zoukankan      html  css  js  c++  java
  • Acwing.835. Trie字符串统计(模板)

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

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

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

    输入格式

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

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

    输出格式

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

    每个结果占一行。

    数据范围

    1N21041≤N≤2∗104

    输入样例:

    5
    I abc
    Q abc
    Q ab
    I ab
    Q ab
    

    输出样例:

    1
    0
    1
    #include <iostream>
    #include<string.h>
    #include<string>
    using namespace std;
    const int maxn = 2e4+20;
    int tree[maxn][26];//存放一个节点的子节点
    int cnt[maxn];//存放当前节点为最后一位字符的单词的个数
    int idx;//总节点数
    
    void tireinsert(const string &str)
    {
        int root=0;
        for(int i=0; i<str.size(); i++)
        {
            int u=str[i]-'a';//映射
            if(!tree[root][u]) tree[root][u]=++idx;
            root=tree[root][u];
        }
        cnt[root]++;
    }
    
    int tirefind(const string &str)
    {
        int root=0;
        for(int i=0; i<str.size(); i++)
        {
            int u=str[i]-'a';
            if(!tree[root][u]) return 0;
            root=tree[root][u];
        }
        return cnt[root];
    }
    
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(0);
        int n;
        cin >> n;
        while(n--)
        {
            string s;
            cin >> s;
            if(s=="I")
            {
                string p;
                cin >> p;
                tireinsert(p);
            }
            else
            {
                string p;
                cin >> p;
                cout << tirefind(p) << endl;;
            }
        }
        return 0;
    }
     
  • 相关阅读:
    SQLAlchemy介绍
    Flask介绍
    逆转的生殖——形而下的EOE补完仪式…
    huiyin
    实验课上
    我的博客今天1岁213天了,我领取了…
    关于直接写屏
    OceanBorn&nbsp;&nbsp;歌曲列表
    Gethsemane
    光辉岁月-Beyond
  • 原文地址:https://www.cnblogs.com/wjc2021/p/11195430.html
Copyright © 2011-2022 走看看