题意:给出一系列的敏感词,如果下面文本以敏感词作为子串,那么输出'*'
思路:简单的AC自动机,如果匹配到当前tire节点是叶子,那么它前面路径字符串都要变为'*"
比赛时看到没什么人做,也就没看题,没想到这么简单...
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5880
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <cctype>
using namespace std;
const int maxn = 1000005;
const int maxnode = 1000005;
bool len[maxn];
struct Aho_Corasick
{
int ch[maxnode][27];
int val[maxnode];
int f[maxnode];
int last[maxnode];
int sz;
void init()
{
sz = 1;
memset(val, 0, sizeof(val));
memset(ch[0], 0, sizeof(ch[0]));
memset(f, 0, sizeof(f));//记得清空
memset(last, 0, sizeof(last));
}
int id(const char &ch)
{
if(ch >= 'A' && ch <= 'Z')
return ch - 'A';
else if(ch >= 'a' && ch <= 'z')
return ch - 'a';
else return 26;
}
void Insert(const char *s)
{
int u = 0, len = strlen(s);
for(int i = 0; i < len; i++)
{
int c = id(s[i]);
if(!ch[u][c])
{
memset(ch[sz], 0, sizeof(ch[sz]));
ch[u][c] = sz++;
}
u = ch[u][c];
}
val[u] = len;
}
void getfail()
{
queue<int> q;
for(int c = 0; c < 26; c++)
{
int u = ch[0][c];
if(u)
{
f[0] = 0;
q.push(u);
last[u] = 0;
}
}
while(!q.empty())
{
int r = q.front();
q.pop();
for(int c = 0; c < 26; c++)
{
int u = ch[r][c];
if(!u) continue;
q.push(u);
int v = f[r];
while(v && !ch[v][c]) v = f[v];
f[u] = ch[v][c];
last[u] = val[f[u]] ? f[u] : last[f[u]];
}
}
}
void print(int i, int j)
{
if(val[j])//如果当前已经是叶子节点,就没有必要找后缀链接了,因为后缀链接是当前的路径字符串的最长后缀
{
for(int k = 0; k < val[j]; k++)
len[i - k] = true;
}
else if(last[j]) print(i, last[j]);
}
void Find(const char *t)
{
int j = 0;
for(int i = 0; t[i]; i++)
{
int c = id(t[i]);
while(j && !ch[j][c]) j = f[j];
j = ch[j][c];
if(val[j])
{
for(int k = 0; k < val[j]; k++)
len[i - k] = true;
}
else if(last[j]) print(i, last[j]);//寻找后缀链接
}
}
};
Aho_Corasick ac;
char s[maxn], T[maxn];
int main()
{
//freopen("g:\\out3.txt", "w", stdout);
int t;
scanf("%d", &t);
while(t--)
{
ac.init();
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
scanf("%s", s);
ac.Insert(s);
}
ac.getfail();
getchar();
gets(T);
memset(len, false, sizeof(len));
ac.Find(T);
for(int i = 0; T[i]; i++)
{
if(len[i])
printf("*");
else
printf("%c", T[i]);
}
printf("\n");
}
return 0;
}