思路:AC自动机正着扫一遍,反着扫一遍。
WA:合成字符串str2时,未进行末尾赋0,导致上次数据保留了下来。
//936ms
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
const int maxs = 5100010,maxp = 1010,maxn = 260010,alpha = 26;
int pc,f[maxn],ch[maxn][alpha],flag[maxn];
char ptr[maxp],str[maxs],str2[maxs];
void ins(char *p) //建树
{
int n = strlen(p),cur = 0;
for(int i=0;i<n;++i)
{
int v = p[i] - 'A';
if(!ch[cur][v]) ch[cur][v] = ++pc;
cur = ch[cur][v];
}
flag[cur]++;
}
void getfail() //bfs找失配函数f
{
queue<int> q;
f[0] = 0;
for(int c=0;c<alpha;++c)
{
int u = ch[0][c];
if(u){
q.push(u);f[u] = 0;
}
}
while(!q.empty())
{
int r = q.front();q.pop();
for(int c=0;c<alpha;++c)
{
int u = ch[r][c];
if(!u) continue;
q.push(u);
int v = f[r];
while(v && !ch[v][c]) v = f[v];
f[u] = ch[v][c];
}
}
}
int find(char *s)
{
int n = strlen(s);
int j = 0,cnt = 0;
for(int i=0;i<n;++i)
{
int c = s[i] - 'A';
while(j && !ch[j][c]) j = f[j];
j = ch[j][c];
int tmp = j;
while(flag[tmp])
{
cnt += flag[tmp];
flag[tmp] = 0;
tmp = f[tmp];
}
}
return cnt;
}
int main()
{
int n,t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
while(n--)
{
scanf(" %s",ptr);
ins(ptr);
}
getfail();
scanf(" %s",str);
int j = 0;
for(int i=0;str[i];++i){ //不规则字符串转化
if(str[i] >= 'A' && str[i] <= 'Z') str2[j++] = str[i];
else
{
++i;
int cnt = 0;
while (str[i]<'A'||str[i]>'Z')
{
cnt = cnt*10 + (str[i]-'0'); //数字部分不止一位
++i;
}
while(cnt--){
str2[j++] = str[i];
}
++i;
}
}
str2[j] = 0; //重要的末尾清0
int ans = 0;
ans += find(str2);
strrev(str2); //strrev(),反转串,reverse
ans += find(str2);
printf("%d\n",ans);
pc = 0;
memset(flag,0,sizeof(flag));
memset(ch,0,sizeof(ch));
}
}