HDU 1711 KMP

题目链接:

[kuangbin带你飞]专题十六 KMP & 扩展KMP & Manacher

Description

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

KMP模板,抽空写一篇有关kmp的博客,便于以后复习。主要思想就是主串不回溯,加上最长前后缀实现不重复比较。不是特别好理解,还要多练习。next跳转表的含义及构造方法是关键。

先附上师兄的博客:KMP算法详解

/************************************************************************* > File Name: hdu_1711_kmp.cpp > Author: dulun > Mail: [email protected] > Created Time: 2016年03月13日 星期日 17时24分34秒 ************************************************************************/

#include<iostream>
#include<stdio.h>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#define LL long long
using namespace std;

int m, n;
int a[1000009];
int b[10009];
int nextval[10009];
const int N = 50086;

void getnext()
{
    int k = 0; 
    nextval[0] = 0;
    for(int i = 1; i < m; i++)
    {
        while(k && b[k] != b[i]) k = nextval[k-1];//k后移
        if(b[k] == b[i]) k++;
        nextval[i] = k;//赋值
    }
}

int kmp()
{
    int j = 0;
    getnext();
    for(int i = 0; i < n; i++)
    {
        while(j && a[i] != b[j]) j = nextval[j-1];//j后移
        if(a[i] == b[j]) j++;
        if(j == m) return i-j+1 + 1;//要加1
    }
    return -1;
}

int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        scanf("%d%d", &n, &m);
        for(int i = 0; i < n; i++) scanf("%d", &a[i]);
        for(int i = 0; i < m; i++) scanf("%d", &b[i]);
        if(m >n) {printf("-1\n"); continue;}
        printf("%d\n", kmp());
    }

    return 0;
}

你可能感兴趣的:(KMP)