输入样例:
5 I abc Q abc Q ab I ab Q ab
输出样例:
1 0 1
地址 https://www.acwing.com/problem/content/description/837/ios
维护一个字符串集合,支持两种操做:web
共有N个操做,输入的字符串总长度不超过 105105,字符串仅包含小写英文字母。ui
第一行包含整数N,表示操做数。spa
接下来N行,每行包含一个操做指令,指令为”I x”或”Q x”中的一种。code
对于每一个询问指令”Q x”,都要输出一个整数做为结果,表示x在集合中出现的次数。xml
每一个结果占一行。blog
1≤N≤2∗104ip
输入样例: 5 I abc Q abc Q ab I ab Q ab 输出样例: 1 0 1
trie 树的模板题ci
解法1 使用trie树解决rem
#include <iostream> using namespace std; const int N = 100010; int son[N][26], cnt[N], idx; char str[N]; 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]; } int main() { int n; scanf("%d", &n); while (n -- ) { char op[2]; scanf("%s%s", op, str); if (*op == 'I') insert(str); else printf("%d\n", query(str)); } return 0; }
解法2 使用哈希解决
#include <iostream> #include <map> #include <string> using namespace std; map<string,int> re; const int N = 100010; int son[N][26], cnt[N], idx; char str[N]; void insert(char str[]){ re[str]++; } int query(char str[]){ return re[str]; } int main() { int n; scanf("%d", &n); while (n -- ) { char op[2]; scanf("%s%s", op, str); if (*op == 'I') insert(str); else printf("%d\n", query(str)); } return 0; }
5 I abc Q abc Q ab I ab Q ab
1 0 1