ac自动机,匹配到的时候记录位置及长度,最后替换成星号即可。
开始MLE和TLE各一发
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
int buff[1000010];
struct Trie
{
int next[500010][26],fail[500010],end[500010];
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 id)
{
int len = id;
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]=id;
}
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(char buf[],int len)
{
int now = root;
int res = 0;
for(int i = 0;i < len;i++)
{
if(buf[i]<'a'||buf[i]>'z')
if(buf[i]>='A'&&buf[i]<='Z') now = next[now][buf[i]-'A'];
else continue;//now = next[now][26];
else now = next[now][buf[i]-'a'];
int temp = now;
while(temp != root)
{
if(end[temp] != -1)
{
buff[i-end[temp]+1]=max(end[temp],buff[i-end[temp]+1]);
}
temp = fail[temp];
}
}
return res;
}
};
char buf[1000010];
Trie ac;
int main()
{
int t,n;
while(scanf("%d",&t) != EOF)
{
while(t--)
{
memset(buff,0,sizeof(buff));
scanf("%d",&n);
ac.init();
for(int i = 1; i <= n; i++)
{
scanf("%s\n",buf);
ac.insert(buf,strlen(buf));
}
ac.build();
gets(buf);
int len = strlen(buf);
ac.query(buf,len);
int x=0;
for(int i=0;i<len;i++)
{
if(x<buff[i])
{
x=buff[i];
}
if(x)
{
buf[i]='*';
x--;
}
}
puts(buf);
}
}
return 0;
}