KMP算法学习——Number Sequence

自己不懂,先记录一下学习的链接:
https://blog.csdn.net/starstar1992/article/details/54913261#commentBox

https://blog.csdn.net/buppt/article/details/78531384

最详细的:
https://blog.csdn.net/v_july_v/article/details/7041827
看完还是不太懂啊

Number Sequence

Given two sequences of numbers : a[1], a[2], …… , a[N], and b[1], b[2], …… , b[M] (1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make a[K] = b[1], a[K + 1] = b[2], …… , a[K + M - 1] = b[M]. If there are more than one K exist, output the smallest one.
Input
The first line of input is a number T which indicate the number of cases. Each case contains three lines. The first line is two numbers N and M (1 <= M <= 10000, 1 <= N <= 1000000). The second line contains N integers which indicate a[1], a[2], …… , a[N]. The third line contains M integers which indicate b[1], b[2], …… , b[M]. All integers are in the range of [-1000000, 1000000].
Output
For each test case, you should output one line which only contain K described above. If no such K exists, output -1 instead.
Sample Input
2
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 1 3
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 2 1
Sample Output
6
-1

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
#define ll long long int 
#define ull unsigned long long int 
#define e 2.718281828459
#define INF 0x7fffffff
#pragma warning(disable:4996)
#define pf printf
#define sf scanf
#define max(a,b) (a)>(b)?(a):(b);
#define pi  acos(-1.0);
#define  eps 1e-9;
#include <cstdlib>
using namespace std;

int a[1000000];
int b[10000];

int n, m;
void Next(int a[], int len,int next[]) {

    next[0] = -1;
    int k = -1;
    int j = 0;
    while (j < len - 1) {
        if (k == -1 || a[j] == a[k]) {
            ++k;
            ++j;
            next[j] = k;//next[j+1]=k+1
        }
        else {
            k = next[k];//递归,寻找更段的前后缀
        }
    }


}


int KMP(int a[],int b[],int next[]) {
    Next(b, m, next);
    int j = 0;
    int k= 0;
    while (j < n&&k < m) {
        if (k == -1 || a[j] == b[k]) {//若相等或只剩最短前后缀(长度为0的前后缀)
            j++;
            k++;
        }
        else {
            k = next[k];//匹配串向右移动j-next[j]
        }
    }

    if (k == m)
        return j - k + 1;
    else
        return -1;
}


int main(void) {
    int t;
    int next[10000];
    sf("%d", &t);
    while(t--) {
        sf("%d%d", &n, &m);
        for (int i = 0; i < n; i++)  sf("%d", &a[i]);
        for (int i = 0; i < m; i++)  sf("%d", &b[i]);
        cout << KMP(a, b, next) << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/jiruqianlong123/article/details/81431159