SCU 4438 Censor(KMP / HASH)

来源:互联网 发布:人工智能 智慧城市 编辑:程序博客网 时间:2024/05/17 23:31

过滤敏感词

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

用一个类似于栈的容器记录已经匹配过的就行了   遇到匹配成功的出栈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[n]==hs)                top-=n;        }        for(int i=0;i<top;i++)            printf("%c",ans[i]);        puts("");    }    return 0;}


0 0
原创粉丝点击