SCU 4438 Censor(Hash)题解

题意:找出字符串p中的w串删除,反复操作,直到找不到w,输出这个串

思路:哈希处理前缀和,如果值相同就删掉。

代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<stdio.h>
#include<string.h>
#include<queue>
#include<cmath>
#include<map>
#include<set>
#include<vector>
using namespace std;
typedef unsigned long long ull;
const int maxn = 5e6 + 10;
const ull seed = 131;
ull bin[maxn], Hash[maxn];
char p[maxn], w[maxn], ans[maxn];
void init(){
    bin[0] = 1;
    for(int i = 1; i < maxn; i++)
        bin[i] = bin[i - 1] * seed;
}
int main(){
    init();
    while(~scanf("%s%s", w + 1, p + 1)){
        int lenw = strlen(w + 1), len = strlen(p + 1);
        ull aim = 0;
        if(lenw > len){
            printf("%s
", p + 1);
        }
        else{
            int point = 1;
            for(int i = 1; i <= lenw; i++)
                aim = aim * seed + w[i] - 'a';
            Hash[0] = 0;
            for(int i = 1; i <= lenw - 1; i++){
                Hash[point] = Hash[point - 1] * seed + p[i] - 'a';
                ans[point++] = p[i];
            }
            for(int i = lenw; i <= len; i++){
                Hash[point] = Hash[point - 1] * seed + p[i] - 'a';
                ans[point] = p[i];
                if(point >= lenw && Hash[point] - Hash[point - lenw] * bin[lenw] == aim){
                    point -= lenw;
                }
                point++;
            }
            for(int i = 1; i < point; i++){
                printf("%c", ans[i]);
            }
            printf("
");
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/KirinSB/p/9895757.html