HDU 5880 Family View

时间:2023-01-31 20:10:33

$AC$自动机。

用$AC$自动机匹配一次,开一个$flag$记录一下以$i$位置为结尾的最长要打$*$多少个字符,然后倒着扫描一次就可以输出了。

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<bitset>
#include<iostream>
using namespace std;
typedef long long LL;
const double pi=acos(-1.0),eps=1e-;
void File()
{
freopen("D:\\in.txt","r",stdin);
freopen("D:\\out.txt","w",stdout);
}
template <class T>
inline void read(T &x)
{
char c=getchar(); x=;
while(!isdigit(c)) c=getchar();
while(isdigit(c)) {x=x*+c-''; c=getchar();}
} const int maxn=;
int flag[maxn];
char buf[maxn]; struct Trie
{
int next[maxn][],fail[maxn],end[maxn],Len[maxn];
int root,L;
int newnode()
{
for(int i = ;i < ;i++) next[L][i] = -;
Len[L]= end[L] = ; L++;
return L-;
}
void init()
{
L = ;
root = newnode();
}
void insert(char buf[])
{
int len = strlen(buf);
int now = root;
for(int i = ;i < len;i++)
{
if(next[now][buf[i]-'a'] == -)
next[now][buf[i]-'a'] = newnode();
now = next[now][buf[i]-'a'];
}
end[now]++;
Len[now]=strlen(buf);
}
void build()
{
queue<int>Q;
fail[root] = root;
for(int i = ;i < ;i++)
if(next[root][i] == -)
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 = ;i < ;i++)
if(next[now][i] == -)
next[now][i] = next[fail[now]][i];
else
{
fail[next[now][i]]=next[fail[now]][i];
Q.push(next[now][i]);
}
}
}
void query(char buf[])
{
int len = strlen(buf);
int now = root;
int res = ;
for(int i = ;i < len;i++)
{
int sign;
if(buf[i]>='A'&&buf[i]<='Z') sign=buf[i]-'A';
else if(buf[i]>='a'&&buf[i]<='z') sign=buf[i]-'a';
else { now=root; continue; }
now = next[now][sign];
int temp = now;
while( temp != root )
{
flag[i]=max(flag[i],Len[temp]);
temp = fail[temp];
}
}
}
}; Trie ac; int main()
{
int T,n; scanf("%d",&T);
while( T-- )
{
scanf("%d",&n); ac.init();
for(int i = ;i < n;i++)
{ scanf("%s",buf); ac.insert(buf); }
ac.build(); getchar(); gets(buf); memset(flag,,sizeof flag);
ac.query(buf); int leng=strlen(buf); int num=; for(int i=leng-;i>=;i--)
{
num=max(num,flag[i]);
if(num==) continue;
else buf[i]='*', num--;
}
printf("%s\n",buf);
}
return ;
}