跳到正文

个人记录

P4824 [USACO15FEB]Censoring S (字符串hash+栈)

DrBit约 4 分钟
原文

这是 2025年10月18日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2021年2月19日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

题目

小提示:没人说过hash一定要一开始全部预处理出来

建立一个栈,每往里面加一个字符就更新一下hash值,如果栈顶往下的一段字符正好等于T就那些字符全pop掉,整个过程是O(N)O(N)的

C++
#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;
}