哈希模板:挑战程序设计P374
Censor
frog is now a editor to censor so-called sensitive words (敏感词).
She has a long text p . Her job is relatively simple -- just to find the first occurence of sensitive word w and remove it.
frog repeats over and over again. Help her do the tedious work.
Input
The input consists of multiple tests. For each test:
The first line contains 1 string w . The second line contains 1 string p .
( 1≤length of w,p≤5⋅106 , w,p consists of only lowercase letter)
Output
For each test, write 1 string which denotes the censored text.
Sample Input
abc
aaabcbc
b
bbb
abc
ab
Sample Output
a
ab
题意:每次删去字符串b中的a串,输出最终剩余的字符
思路: 将a串哈希为一个整数,将b字符依次放入栈中,当长度大于等于a串的长度时,比较哈希值,相同则删除,继续操作
CODE:
#include<stdio.h>
#include<vector>
#include<iostream>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
typedef unsigned long long ull;
const ull B =1e8+7;//哈希的基数
const int N=5*1e6+10;
ull bh[N];
char a[N],b[N],str[N];
int main()
{
while(~scanf("%s%s",a,b))
{
int a1=strlen(a),b1=strlen(b);
if(a1>b1)
{
printf("%s\n",b);
continue;
}
ull t=1;
for(int i=0; i<a1; i++)
{
t*=B;
}
ull ah=0;
bh[0]=0;
for(int i=0; i<a1; i++) ah=ah*B+a[i];
// printf("%llu \n",ah);
int top=0;
for(int i=0;i<b1;i++)
{
str[top++]=b[i];
bh[top]=bh[top-1]*B+b[i];
if(top>=a1&&bh[top]-bh[top-a1]*t==ah)
{
//printf("%d\n",top);
top-=a1;
}
}
for(int i=0;i<top;i++)
{
printf("%c",str[i]);
}
printf("\n");
}
}