Number Sequence HDU - 1711 (KMP算法理解+模板)

先放一个大佬的链接,ke'y可以说是讲的非常详细了:https://blog.csdn.net/v_july_v/article/details/7041827,感谢大佬分享

这篇对部分匹配值介绍很详细:http://www.doc88.com/p-2929643037053.html

说一下我对kmp的理解吧(不一定正确,前辈多zhi'指教):

     kmp算法的优越性在于不必将p上的字符跟s上的每个字符都作比较,进而节省时间。

    举个例子:“acbacd”这个字符串匹配到最后一个字符错了、于是我看它前面的几个字符特点很明显我们不用重新从头开始比、而可以从字符“b”开始比、因为“acbac”的前缀“ac”==后缀“ac”、相当于间接的比过。

    nexts[ ]数组就是将部分匹配值向后挪1,第一个补 -1

例题:

Number Sequence

 HDU - 1711    

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

题意:T组数据,s有n个数,p有m个数,问从s中的那个位置开始可以将p匹配上

思路:kmp算法模板题

AC代码:

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define maxn1 1000005
#define maxn2 10005
#define INF 0x3f3f3f3f
#define LL long long
#define ULL unsigned long long
#define E 1e-8
#define mod 1000000007
#define P pair
using namespace std;
 
int n,m;
int s[maxn1];
int p[maxn2];
int nexts[maxn2];
 
void GetNexts()
{
    int j=0,k=-1;
    nexts[0] = -1;
    while(j

 

你可能感兴趣的:(数据结构-KMP)