P4824 [USACO15FEB]Censoring S (字符串hash+栈)
题目
小提示:没人说过hash一定要一开始全部预处理出来
建立一个栈,每往里面加一个字符就更新一下hash值,如果栈顶往下的一段字符正好等于T就那些字符全pop掉,整个过程是
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define ull unsigned long long
const int MAXN = 3e6 + 50;
const ull base = 19260817;
const ull base2 = 233317;
char a[MAXN], b[MAXN];
ull mi[MAXN], hsha[MAXN], hshb[MAXN], hsha2[MAXN], hshb2[MAXN], mi2[MAXN];
int s[MAXN], top, lena, lenb;
void init()
{
mi[0] = 1;
mi2[0] = 1;
for (int i = 1; i <= lena; ++i)
{
mi[i] = mi[i - 1] * base;
mi2[i] = mi2[i - 1] * base2;
}
for (int i = 1; i <= lenb; ++i)
{
hshb[i] = hshb[i - 1] * base + b[i];
hshb2[i] = hshb2[i - 1] * base2 + b[i];
}
}
int main()
{
// freopen("test.in", "r", stdin);
// freopen("test.out", "w", stdout);
scanf("%s%s", a + 1, b + 1);
lena = strlen(a + 1);
lenb = strlen(b + 1);
if (lena < lenb)
{
for (int i = 1; i <= lena; ++i)
putchar(a[i]);
return 0;
}
init();
while (top < lenb - 1)
{
top++;
s[top] = top;
hsha[top] = hsha[top - 1] * base + a[top];
hsha2[top] = hsha2[top - 1] * base2 + a[top];
}
int ans = 0;
for (int i = lenb; i <= lena; ++i)
{
s[++top] = i;
hsha[top] = hsha[top - 1] * base + a[i];
hsha2[top] = hsha2[top - 1] * base2 + a[i];
if (hsha[top] - hsha[top - lenb] * mi[lenb] == hshb[lenb])
if (hsha2[top] - hsha2[top - lenb] * mi2[lenb] == hshb2[lenb])
{
// cout << i << " " << top << endl;
top -= lenb;
ans++;
}
}
for (int i = 1; i <= top; ++i)
putchar(a[s[i]]);
return 0;
}