Description
给出 n n 个模式串和一个文本串,模式串只由小写字母组成,要求把文本串中出现的模式串(不区分大小写)全部转化成输出
Input
第一行一整数 T T 表示用例组数,每组用例首先输入一整数表示模式串个数,之后输入 n n 个只由小写字母组成的模式串,最后输入一个文本串,文本串串长不超过,模式串总串长不超过 106 10 6
Output
把文本串中出现的模式串全部转化为 ∗ ∗ 后输出
Sample Input
1
3
trump
ri
o
Donald John Trump (born June 14, 1946) is an American businessman, television personality, author, politician, and the Republican Party nominee for President of the United States in the 2016 election. He is chairman of The Trump Organization, which is the principal holding company for his real estate ventures and other business interests.
Sample Output
D*nald J*hn ***** (b*rn June 14, 1946) is an Ame**can businessman, televisi*n pers*nality, auth*r, p*litician, and the Republican Party n*minee f*r President *f the United States in the 2016 electi*n. He is chairman *f The ***** *rganizati*n, which is the p**ncipal h*lding c*mpany f*r his real estate ventures and *ther business interests.
Solution
自动机裸题,对于每个匹配,假设是文本串的 [L,R] [ L , R ] 区间为一个模式串,对该区间每个位置加一个标记,那么只要一个位置有非零个标记说明该位置需要变成 ∗ ∗ 输出,区间更新用前缀和优化,即位置加一个标记, R R <script type="math/tex" id="MathJax-Element-13">R</script>位置减一个标记,求一遍前缀和即得到每个位置的标记数
Code
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
typedef long long ll;
#define maxn 1000005
int sum[maxn],d[maxn];
struct Trie
{
int next[maxn][26],fail[maxn],end[maxn];
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]=1,d[now]=len;
}
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]);
}
}
}
void solve(char buf[])
{
int len=strlen(buf);
int now=root;
for(int i=0;i<len;i++)
{
int k;
if(buf[i]>='A'&&buf[i]<='Z')k=buf[i]-'A';
else if(buf[i]>='a'&&buf[i]<='z')k=buf[i]-'a';
else continue;
now=next[now][k];
int temp=now;
while(temp!=root)
{
if(end[temp])
{
sum[i+1]--;
sum[i-d[temp]+1]++;
break;
}
temp=fail[temp];
}
}
}
};
char buf[maxn];
Trie ac;
int main()
{
int T;
int n;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
getchar();
ac.init();//初始化
for(int i=0;i<n;i++)
{
gets(buf);
ac.insert(buf);//插入模式串
}
ac.build();//建树
gets(buf);
memset(sum,0,sizeof(sum));
ac.solve(buf);
ll res=0;
int len=strlen(buf);
for(int i=0;i<len;i++)
{
res+=sum[i];
if(res<=0)printf("%c",buf[i]);
else printf("*");
}
printf("\n");
}
return 0;
}