牛客網-白兔的字符串(字符串哈希)

解題思路:

好像使用map會超時,所以採用鏈式哈希。

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 2000005;
const long long base = 97;
const int mod = 196613;

char T[maxn];
unsigned long long Hash[maxn];
unsigned long long has[maxn];
int head[maxn], tot;

struct node{
    unsigned long long x;
    int nxt;
}edges[maxn];

void addEdge(unsigned long long x)
{
//    cout << "gg"<< x<<endl;
    int u = x%mod;
    edges[tot] = {x,head[u]};
    head[u] = tot++;
}

char str[maxn];

int Find(unsigned long long x)
{
//    cout <<"kk"<<x<<endl;
    int u = x%mod;
    for(int i = head[u]; ~i; i = edges[i].nxt)
    {
        if(edges[i].x == x)
            return 1;
    }
    return 0;
}

int main()
{
    scanf("%s", T+1);
    Hash[0] = 1;
    for(int i = 1; i < maxn; i++)
        Hash[i] = Hash[i-1]*base;
    int len = strlen(T+1);
    for(int i = 1; i <= len; i++)
        T[i+len] = T[i];
    memset(head,-1,sizeof(head));
    tot = 1;
    for(int i = 1; i <= 2*len; i++)
    {
        has[i] = has[i-1]*base+(T[i]-'a'+1);
//        cout << "1 "<<i<<" "<<has[i]<<endl;
        if(i>=len) addEdge(has[i]-has[i-len]*Hash[len]);
    }

    int t;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%s", str+1);
        int l = strlen(str+1);
        int ans = 0;
        for(int i = 1; i <= l; i++)
        {
            has[i] = has[i-1]*base+(str[i]-'a'+1);
//            cout <<"2 "<<i<<" "<<has[i]<<endl;
            if(i>=len) ans+=Find(has[i]-has[i-len]*Hash[len]);
        }
        printf("%d\n", ans);
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章