[防hack]双字符串哈希

Codeforces Round 855 (Div. 3)D. Remove Two Letters

借鉴知乎大佬(Codeforces Round #855 div3 A~E - 知乎 (zhihu.com)

#include<bits/stdc++.h>
#define endl "\n"
using namespace std;

const int N = 2e6+10, P1 = 131, P2 = 13331;
typedef unsigned long long ull;
typedef pair<ull, ull> PUU;

int n;
char s[N];
ull h1[N], p1[N];
ull h2[N], p2[N];

void init1()
{
    p1[0] = p2[0] = 1;
    for(int i = 1; i <= N - 1; i++) 
    {
        p1[i] = p1[i - 1] * P1;
        p2[i] = p2[i - 1] * P2;
    }
}

void init2()
{
    for(int i = 1; i <= n; i++) 
    {
        h1[i] = h1[i - 1] * P1 + s[i];
        h2[i] = h2[i - 1] * P2 + s[i];
    }
}

ull get(ull h[], ull p[], int l, int r)
{
    return h[r] - h[l - 1] * p[r - l + 1];
}

void solve()
{
    
    cin >> n >> (s + 1);
    init2();
    set<PUU> st;
    for(int i = 1; i <= n - 1; i++)
    {
        ull pre1 = h1[i - 1], suf1 = 0;
        ull pre2 = h2[i - 1], suf2 = 0;
        if(i < n - 1) 
        {
            suf1 = get(h1, p1, i + 2, n);
            suf2 = get(h2, p2, i + 2, n);
        }
        ull res1 = pre1 * p1[n - i - 1] + suf1;
        ull res2 = pre2 * p2[n - i - 1] + suf2;
        if(!st.count(PUU(res1, res2))) st.insert(PUU(res1, res2));
    }
    cout << st.size() << endl;
}
int main()
{
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    init1();
    int t;
    cin >> t;
    while(t--) solve();
    return 0;
}

 

posted @ 2023-05-11 22:00  Thecode_Wm  阅读(79)  评论(0)    收藏  举报