LOJ 103 substring lookup - instead of using hash algorithm kmp

The meaning of problems

Given two strings $ s_1, s_2 $, $ request number appears in S_2 $ $ $ in S_1.

analysis

Preprocessing the two hash value string, and the bit-wise comparison.

Time complexity is $ O (n + m) $, $ and $ KMP algorithm is the same.

Possible constant little freshman, there is the $ next $ array can not use the $ kmp $.

#include <bits/stdc++.h>
using namespace std;

typedef unsigned long long ull;
const ull base = 233;
const int maxn = 1e6 + 10;

ull h[maxn], p[maxn], ha;
char s1[maxn], s2[maxn];

int main()
{
    scanf("%s%s", s1+1, s2+1);
    int n = strlen(s1+1), m = strlen(s2+1);
    for(int i = 1;i <= m;i++)  ha = ha * base + (ull)s2[i];
    p[0]=1;
    for(int i = 1;i <= n;i++)
    {
        h[i] = h[i-1]*base + (ull)s1[i];
        p[i] = p[i-1] * base;
    }
    int l=1, r = m, ans = 0;
    while(r <= n)
    {
        if(h[r] - h[l-1]*p[m] == ha)  ans++;
        l++, r++;
    }
    printf("%d\n", ans);
    return 0;
}

 

 

Reference Links: https://zhuanlan.zhihu.com/p/78418415

Guess you like

Origin www.cnblogs.com/lfri/p/11375376.html