[Trie树][YbtOJ]A. 【例题1】前缀统计
解析
Trie树基础题, 将 \(s\) 串全部加到Trie树里面, 然后记录以某个节点为终点的单词的个数 val[], 然后将询问串 \(T\) 搜索一遍, 遍历过完的点就讲 \(val[hhd]\) 给加上.
Code
#include <bits/stdc++.h>
#define N 100005
using namespace std;
char se[N];
int n, m;
struct Trie
{
int tag, val[N], st[N][30];
Trie ()
{
tag = 1;
memset (val, 0, sizeof (val));
memset (st[0], 0, sizeof (st[0]));
}
void insert (char *s)
{
int hhd = 1, len = strlen (s + 1);
for (int i = 1; i <= len; ++ i)
{
int c = s[i] - 'a';
if (!st[hhd][c])
st[hhd][c] = ++ tag;
hhd = st[hhd][c];
}
val[hhd] ++;
}
int search (char *s)
{
int hhd = 1, len = strlen(s + 1), add = 0;
for (int i = 1; i <= len; ++ i)
{
int c = s[i] - 'a';
if (!st[hhd][c])
{
return add;
}
hhd = st[hhd][c];
add += val[hhd];
}
return add;
}
}tree;
int main ()
{
scanf ("%d%d", &n, &m);
for (int i = 1; i <= n; ++ i)
{
scanf ("%s", se + 1);
tree.insert (se);
}
for (int i = 1; i <= m; ++ i)
{
scanf ("%s", se + 1);
int ans = tree.search (se);
printf ("%d\n", ans);
}
return 0;
}