题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5880
更新了模板,另外读入的时候需要注意用gets()
模板(kuangbin):
const int MAX=500005;
struct Trie
{
int next[MAX][26],fail[MAX],end[MAX];
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(char *buf)
{
int len=strlen(buf);
int now=root;
int res=0;
for (int i=0;i<len;i++)
{
now=next[now][buf[i]-'a'];
int temp=now;
while (temp!=root)
{
res+=end[temp];
end[temp]=0;
temp=fail[temp];
}
}
return res;
}
};
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+10;///多个模式串长度
const int N=1e6+10;///文章长度
const int lettersize=26;///看种类
int ans[maxn];
char s[maxn];
char no[N];
vector<pair<int,int>> a;
const int MAX=1e6+10;
struct Trie
{
int next[MAX][26],fail[MAX],end[MAX];
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();
a.clear();
memset(ans,0,sizeof ans);
}
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'];
}
// int temp=end[now];
// if(temp)
// printf("temp=%d\n",temp);
end[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]);
}
}
}
int query(char *buf)
{
int len=strlen(buf);
int now=root;
int res=0;
for (int i=0;i<len;i++)
{
int pos;
if(buf[i]>='a'&&buf[i]<='z') pos=buf[i]-'a';
else if(buf[i]>='A'&&buf[i]<='Z') pos=buf[i]-'A';
else
{
// now=root;
continue;
}
// printf("pos=%d\n",pos);
now=next[now][pos];
int temp=now;
while (temp!=root)
{
// printf("ok\n");
ans[i+1]++;
ans[i-end[temp]+1]--;
temp=fail[temp];
}
}
return res;
}
}ac;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
ac.init();
int k;
scanf("%d",&k);
char ch;
for(int i=1;i<=k;i++)
scanf("%s",s),ac.insert(s);
getchar();
gets(no);
ac.build();
// printf("no=%s",no);
ac.query(no);
int bo=0;
// printf("asize=%d\n",a.size());
int len=strlen(no);
int sum=0;
for(int i=0;i<len;i++)
{
sum+=ans[i];
if(!sum)printf("%c",no[i]);
else
printf("*");
}
printf("\n");
}
return 0;
}