#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<cstdio>
#include<cmath>
#include<queue>
#include<map>
#include<string>
#include<set>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int N = 2e6 + 5;//不给数据范围,RE了好几次
int son[N][26];
int cnt[N], idx;
//cnt[i]是指以编号为i结尾的字符串有多少个,i是一个idx
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];
//这里相当于,字符串str和在树中的查找在同步进行
//str在往后遍历,trie树也在往下遍历
cnt[p]++;
//这里的p是指idx,也就是字母的编号,即使
}
}
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(void) {
char str[N];
while (gets(str)) {
if (str[0] == '\0')
break;
insert(str);
}
while (~scanf("%s", str))
printf("%d\n", query(str));
return 0;
}
HDU - 1251 统计难题(trie模板记录)
最新推荐文章于 2021-11-09 00:20:03 发布