这是一个错误的AC代码。
#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <algorithm>
#include <queue>
const int MAXN = 1e6 + 123;
using namespace std;
int N , p[MAXN];
char t[MAXN] , s[MAXN];
int now = 1 , ans = 0;
struct Trie{
int isword;
int son[26];
}e[MAXN];
queue<int> q;
int main() {
scanf ("%d" , &N);
for (int i = 1 ; i <= N ; i ++) {
scanf ("%s" , s + 1);
int j , pp = 1;
for (j = 1 ; s[j] ; j ++) {
if (e[pp].son[s[j] - 'a'] == 0) {
now ++;
e[pp].son[s[j] - 'a'] = now;
}
pp = e[pp].son[s[j] - 'a'];
}
e[pp].isword ++;
}
scanf ("%s" , t + 1);
q.push(1);
for (int i = 0 ; i < 26 ; i ++)
e[0].son[i] = 1;
int j = 1;
p[1] = 0;
while (!q.empty()) {
int h = q.front();
q.pop();
for (int i = 0 ; i < 26 ; i ++) {
if (e[h].son[i]) {
j = p[h];
while (j > 0 && e[j].son[i] == 0)
j = p[j];
p[e[h].son[i]] = e[j].son[i];
q.push(e[h].son[i]);
}
else
e[h].son[i] = e[p[h]].son[i];
}
}
j = 1;
for (int i = 1 ; t[i] ; i ++) {
j = e[j].son[t[i] - 'a'];
ans += e[j].isword;
e[j].isword = 0;
}//在这里我没有沿着fail链往回找答案。
//这导致了若存在某个单词
//是另一个单词的子串(非前缀),
//则前者被遗漏。
printf ("%d\n" , ans);
return 0;
}
建议增加数据:
5
she
he
say
shr
her
yasherhs
参考资料 Keywords Search