sequence

Topic description

Given a sequence A with n numbers and a sequence B with m (m<=n) numbers.

Ask how many consecutive subsequences of length m A k ,A k+1 ,...,A k+m-1 exist in A such that for any 1<=i, j<=m satisfies Ak+i-1 -B i =A k+j-1 -B j

enter

The first line contains two integers n, m (1 <= m <= n <= 10 6 )

The next line contains n integers describing the sequence A (A i <= 10 9 )

The next line contains m integers describing the sequence B (B i <= 10 9 )

output

output a number to indicate the answer

sample input

7 4
6 6 8 5 5 7 4
7 7 9 6

Sample output

2

Ideas:

I thought of using kmp for this question, but at first I thought that the difference between the two numbers is equal to the difference between the first two numbers (special consideration for the first number), but this is problematic and troublesome.

A classmate told me that you can find the difference between these numbers:

The example can be reduced to: 7 4

                    0  2 -3  0  2 -3

                    0  2 -3

This becomes a pure kmp.

#include <iostream>

using namespace std;

int n, m;
// n main string length, m pattern string length
const int N = 1000100;
int nextt[N];
int x[N]; // pattern string
int y[N]; // main string

// process the pattern string
void kmp_pre() {
    int i, j;
    j = nextt[0] = -1;
    i = 0;
    while(i<m) {
        while(-1!=j && x[i]!=x[j]) j=nextt[j];
        nextt[++i] = ++j;
    }
}

int kmp_count() {
    int i, j;
    int years = 0;
    kmp_pre ();
    i = 0, j = 0;
    while(i < n) {
        while(-1!=j && y[i]!=x[j]) j=nextt[j];
        i++; j++;
        if(j >= m) {
            years ++;
            j = nextt[j];
        }
    }
    return ans;
}

intmain()
{
    cin >> n >> m;
    for(int i=0; i<n; i++){
        cin >> y[i];
    }
    for(int i=0; i<m; i++) {
        cin >> x[i];
    }
    n --, m --;

    for(int i=0; i<n; i++){
        y[i] = y[i+1]-y[i];
    }
    for(int i=0; i<m; i++){
        x[i] = x[i+1]-x[i];
    }
    
    // output the number obtained by kmp
    cout << kmp_count() << endl;
    return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326076661&siteId=291194637