SCU 4438 字符串哈希

 题意:一个敏感词w和一个文本p,在文本中不断地删除敏感词w,求最后的剩下的文本p。

题解:求出敏感词的hash值,定p的每一个字符都是以第一个字符开始的一个句子,求出它们的hash值入栈,当某一段的hash值等于敏感词的hash值时,将这段字符出栈。

 

#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

#define maxn 5000006
long long hash=100007;
long long hash_w;
long long hash_p[maxn];
long long hash_pow[maxn];

char p[maxn],w[maxn];
char stack[maxn];
int len;

void init()
{
    hash_pow[0]=1;
    for(int i=1;i<maxn;i++)
        hash_pow[i]=hash_pow[i-1]*hash;
}

bool check(int pos)
{
    if(pos>=len && hash_p[pos]-hash_p[pos-len]*hash_pow[len]==hash_w)
        return true;
    return false;
}

int main()
{
    init();
    while(~scanf("%s%s",w,p))
    {
        len=strlen(w);
        hash_w=0;
        for(int i=0;*(w+i);i++)
            hash_w=hash_w*hash+*(w+i);
        int top=0;
        for(int i=0;*(p+i);i++)
        {
            stack[top++]=*(p+i);
            hash_p[top]=hash_p[top-1]*hash+*(p+i);
            if(check(top)) top-=len;
        }
        for(int i=0;i<top;i++)
            printf("%c", stack[i]);
        printf("\n");
    }
    return 0;
}
View Code

 

posted on 2016-08-03 08:12  猫哥小俊  阅读(321)  评论(1编辑  收藏  举报

导航