【模板题】 字符串统计

传送门

题意

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

  • ((I,x))向集合中插入一个字符串(x)
  • ((Q,x))询问一个字符串在集合中出现了多少次。

字符仅包含小写字母

数据范围

(1leq N leq 2 imes 10^{4})
(1 leq |S|leq 10^{5})

题解

利用字典树统计字符串数目模板题,在字典树中,每条边表示的是字符串中的字符,
在每个字符串的终止节点来计算数目

Code

#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for(int i=a;i<n;i++)
#define per(i,a,n) for(int i=n-1;i>=a;i--)

const int N=1e5+10;

int trie[N][26],cnt[N],tot=1;
char s[N];
int n;

void insert(char s[])
{
    int p=1;
    for(int i=0;s[i];i++)
    {
        int c=s[i]-'a';
        if(!trie[p][c]) trie[p][c]=++tot;
        p=trie[p][c];
    }
    cnt[p]++;
}

int query(char s[])
{
    int p=1;
    for(int i=0;s[i];i++) // c++字符串结尾是0
    {
        int c=s[i]-'a';
        if(!trie[p][c]) return 0;
        p=trie[p][c];
    }
    return cnt[p];
}

void solve()
{
    cin>>n;
    char op[2];
    while(n--)
    {
        cin>>op>>s;
        if(op[0]=='I')  insert(s);
        else cout<<query(s)<<endl;
    }
}
int main()
{
    solve();
}
原文地址:https://www.cnblogs.com/hhyx/p/13386489.html