AC自动机 , but要有一点小优化,要不然TLE
#include <algorithm>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <queue>
#include <ctype.h>
using namespace std;
bool vis[350010];
struct Tree
{
int next[350010][26], _end[350010], fail[350010];
int root, L;
int newnode( )
{
for( int i = 0; i < 26; i++ )
next[L][i] = -1;
_end[L++] = 0;
return L - 1;
}
void init()
{
L = 0;
root = newnode();
}
void insert( char buf[] )
{
int len = strlen(buf);
int now = root;
for( int i = 0; i < len ; i++ )
{
if(next[now][buf[i] - 'A'] == -1)
next[now][buf[i] - 'A'] = newnode();
now = next[now][buf[i] - 'A'];
}
_end[now]++;
}
void build( )
{
queue<int> Q;
fail[root] = root;
for( int i = 0; i < 26; i++)
{
if(next[root][i] == -1)
next[root][i]= root;
else
{
fail[next[root][i]] = root;
Q.push(next[root][i]);
}
}
while(!Q.empty())
{
int now = Q.front();
Q.pop();
for( int i = 0; i < 26; i++ )
{
if(next[now][i] == -1)
next[now][i] = next[fail[now]][i];
else
{
fail[next[now][i]] = next[fail[now]][i];
Q.push(next[now][i]);
}
}
}
}
int query(string buf)
{
int len = buf.length();
int now = root;
int res = 0;
for( int i = 0; i < len; i++ )
{
if(buf[i] == '[' || buf[i] == ']')
{
int num = 0, c;
if(isdigit(buf[++i]))
{
while(isdigit(buf[i]))
{
num = num * 10 + (buf[i] -'0');
i++;
if(num > 1000) break;//优化1
}
while(isdigit(buf[i])) i++;
c = buf[i] - 'A';
i++;
}
else
{
c = buf[i] - 'A';
i++;
while(isdigit(buf[i]))
{
num = num * 10 + (buf[i] -'0');
i++;
}
}
for( int j = 0; j < num; j++)
{
now = next[now][c];
int temp = now;
while(temp != root && !vis[temp])//优化2
{
if(!vis[temp])
{
res += _end[temp];
vis[temp] = 1;
}
temp = fail[temp];
}
}
}
else
{
now = next[now][buf[i] - 'A'];
int temp = now;
while(temp != root)
{
if(!vis[temp])
{
res += _end[temp];
vis[temp] = 1;
}
temp = fail[temp];
}
}
}
return res;
}
};
char buf[1010];
Tree ac;
string res;
int main()
{
int T, n;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
ac.init();
memset(vis, false, sizeof(vis));
for( int i = 0; i < n; i++)
{
scanf("%s",&buf);
ac.insert(buf);
}
ac.build();
cin >> res;
int ans = 0;
memset(vis, 0, sizeof(vis));
ans += ac.query(res);
reverse(res.begin(), res.end());
ans += ac.query(res);
printf("%d\n",ans);
}
return 0;
}