码迷,mamicode.com
首页 > 其他好文 > 详细

【模板】字符串哈希

时间:2018-10-24 22:04:41      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:模板   scan   ons   can   mes   mat   ace   ++   哈希   

取进制数为131,每次\(O(N)\)时间预处理出幂次和母串的滚动哈希值。

代码如下

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e6+10;
const int base=131;

char s1[maxn],s2[maxn];
unsigned long long power[maxn],tot,h[maxn],l1,l2,ans;

int main(){
    scanf("%s%s",s1+1,s2+1);
    l1=strlen(s1+1),l2=strlen(s2+1);

    power[0]=1;
    for(int i=1;i<=l1;i++)power[i]=power[i-1]*base;
    for(int i=1;i<=l1;i++)h[i]=h[i-1]*base+s1[i]-‘A‘;//滚动哈希
    for(int i=1;i<=l2;i++)tot=tot*base+s2[i]-‘A‘;

    for(int i=l2;i<=l1;i++)
        if(tot==h[i]-h[i-l2]*power[l2])//子串哈希值
            ++ans;
    printf("%d\n",ans);
    return 0;
}

【模板】字符串哈希

标签:模板   scan   ons   can   mes   mat   ace   ++   哈希   

原文地址:https://www.cnblogs.com/wzj-xhjbk/p/9846035.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!