【模板題】 字串統計
阿新 • • 發佈:2020-07-27
題意
維護一個字串集合,支援兩種操作:
I x
向集合中插入一個字串\(x\);Q x
詢問一個字串在集合中出現了多少次。
字元僅包含小寫字母
資料範圍
\(1\leq N \leq 2\times 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--) #define ll long long const int N=1e5+10; int trie[N][26],cnt[N],tot=1; char s[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++){ int c=s[i]-'a'; if(!trie[p][c]) return 0; p=trie[p][c]; } return cnt[p]; } int main(){ int n; scanf("%d",&n); char op[2]; while(n--){ scanf("%s",op); scanf("%s",s); if(*op=='I') insert(s); else printf("%d\n",query(s)); } }