831. KMP string + string hashing to solve KMP

Given a pattern string S and a template string P, all strings contain only uppercase and lowercase English letters and Arabic numerals.

The template string P appears multiple times as a substring in the pattern string S.

Find the starting index of all occurrences of the template string P in the pattern string S.

Input format
Input the integer N in the first line, which represents the length of the string P.

Enter the string P on the second line.

The third line inputs the integer M, which represents the length of the string S.

Enter the string S on the fourth line.

Output format
One line, output the starting subscripts of all occurrences (the subscripts start counting from 0), and the integers are separated by spaces.

Data range
1≤N≤105
1≤M≤106
Input sample:
3
aba
5
ababa
output sample:
0 2

在这里插入代码片
#include<bits/stdc++.h>
using namespace std;
const int N = 1000010, P = 131;
int hs[N], p[N], hp[N];
typedef unsigned long long ULL;
char s[N], pt[N];

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

int main()
{
    
    
    int n, m;
    cin >> n >> pt+1 >> m >> s+1;
    
    p[0] = 1;
    for(int i=1; i<=m; i++) {
    
    
        p[i] = p[i-1] * P;
        hs[i] = hs[i-1] * P + s[i];
    }
    
    for(int i=1; i<=n; i++) hp[i] = hp[i-1] * P + pt[i];
    
    int r = n;
    while(r <= m) {
    
    
        if(hp[n] == get(r-n+1, r)) {
    
    
            cout << r-n << ' ';
        }
        r++;
    }
    
    return 0;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324119425&siteId=291194637