您的位置:首页 > 其它

SCU 4438 Censor(KMP / HASH)

2015-10-01 16:04 253 查看
过滤敏感词

其实就是找子串 就是记录答案的时候不一样

用一个类似于栈的容器记录已经匹配过的就行了 遇到匹配成功的出栈n个就行了

KMP 为了出栈后能继续之前的匹配 多一个数组记录栈中当前元素的失配位置 - -

KMP:

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 5e6+10;
struct KMP
{
int f[MAXN];
void getFail(char S[])
{
int i=0,j=-1;
int len=strlen(S);
f[0]=-1;
while (i<len)
{
if (j==-1||S[i]==S[j])
{
i++,j++;
f[i]=j;
}
else
j=f[j];
}
}
///Whether S is a substring of T
///Or whether T has S;
int jmp[MAXN];
char ans[MAXN];
int beat(char T[],char S[])
{
int i=0,j=0,top=0;
int n=strlen(T);
int m=strlen(S);
getFail(S);
for(i=0;i<n;i++)
{
while(j!=-1&&T[i]!=S[j])
{
int t=j-f[j];
j=f[j];
}
j++;
jmp[top]=j;
ans[top]=T[i];
ans[++top]=0;
jmp[i]=j;
if(j==m)
{
top-=m;
ans[top]=0;
j=jmp[top-1];
}
}
puts(ans);
return 0;
}
}soul;

char s[MAXN],t[MAXN];

int main()
{
while(scanf("%s%s",s,t)!=EOF)
soul.beat(t,s);
return 0;
}


HASH:

#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ULL;
const int MAXN  = 5e6+100;
const int SEED = 13331;

ULL ht[MAXN],hs;
ULL xl[MAXN];
char s[MAXN],t[MAXN],ans[MAXN];
int main()
{
xl[0]=1;
for(int i=1;i<MAXN;i++)
xl[i]=xl[i-1]*SEED;
while(scanf("%s%s",s,t)!=EOF)
{
int n=strlen(s);
hs=0;
for(int i=0;i<n;i++)
hs=hs*SEED+s[i];
int top=0;
int m=strlen(t);
ht[0]=0;
for(int i=0;i<m;i++)
{
ans[top++]=t[i];
ht[top]=ht[top-1]*SEED+t[i];
if(top>=n&&ht[top]-ht[top-n]*xl
==hs)
top-=n;
}
for(int i=0;i<top;i++)
printf("%c",ans[i]);
puts("");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: