很温柔的一道题;
建树的时候,用val数组记录每个节点是几个单词的末尾节点,print函数将末尾是几个节点加上,每次加完记得把val清零;
比如
input:
1
2
abc
abc
abc
output:
2
input:
1
1
abc
abcabc
output:
1
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 500010;
int T, n;
int num;
char t[2 * maxn];
int ch[maxn][26];
int val[maxn];
int last[maxn];
int f[maxn];
int sz;
struct Trie{
int idx(char x){ return x - 'a'; }
void insert(char *s){
int u = 0, n = strlen(s);
for (int i = 0; i < n; i++){
int c = idx(s[i]);
if (!ch[u][c]){
ch[u][c] = sz++;
}
u = ch[u][c];
}
val[u]++;
}
void init(){
memset(ch, 0, sizeof(ch));
memset(val, 0, sizeof(val));
sz = 1;
for (int i = 0; i < n; i++){
char str[55]; scanf("%s", str);
insert(str);
}
}
void build(){
queue<int> q;
memset(f, 0, sizeof(f));
memset(last, 0, sizeof(last));
for (int i = 0; i < 26; i++){
int u = ch[0][i];
if (u){ q.push(u); }
}
while (!q.empty()){
int r = q.front(); q.pop();
for (int i = 0; i < 26; i++){
int u = ch[r][i];
if (!u) continue;
q.push(u);
int v = f[r];
while (v && !ch[v][i]) v = f[v];
f[u] = ch[v][i];
last[u] = val[f[u]] ? f[u] : last[f[u]];
}
}
}
void print(int j){
if (j){
num += val[j];
val[j] =0 ; //清零避免重复加
print(last[j]);
}
}
void find(char *t){
int n = strlen(t);
int j = 0;
for (int i = 0; i < n; i++){
int c = idx(t[i]);
while (j&&!ch[j][c]) j = f[j];
j = ch[j][c];
if (val[j]) print(j);
else if (last[j]) print(last[j]);
}
}
};
int main(){
Trie ac;
cin >> T;
while (T--){
num = 0;
scanf("%d", &n);
ac.init();
scanf("%s", t);
ac.build();
ac.find(t);
printf("%d\n", num);
}
}