### HDU1711 ——Number Sequence（KMP模板題）

`````` Given two sequences of numbers : a, a, ...... , a[N], and b, b, ...... , b[M] (1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make a[K] = b, a[K + 1] = b, ...... , 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, a, ...... , a[N]. The third line contains M integers which indicate b, b, ...... , 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 <iostream>
#include <cstdio>

using namespace std;

int next1;
int board;
int str;
int N,M;

void getNext(){

int k = -1;
int j = 0;
next1 = -1;//next數組最好是從0開始要不然會很麻煩
while(j<M){
if(k == -1 || board[j] == board[k]){
if(board[j+1] == board[k+1]){
next1[++j] = next1[++k];
}
else next1[++j] = ++k;
}
else {
k = next1[k];
}
}
}

int Find(){//返回匹配到的位置
getNext();
int temp1 = 0,temp2 = 0;
while(temp1<N && temp2<M){
if(temp2 == -1 || str[temp1] == board[temp2]){
temp1++;temp2++;
}
else{
temp2 = next1[temp2];
}
}
if(temp2 == M)return temp1-temp2;
else return -1;
}

int main(){

int T;
cin>>T;
while(T--){
scanf("%d %d",&N,&M);
for(int i=0 ; i<N ; i++)scanf("%d",&str[i]);
for(int i=0 ; i<M ; i++)scanf("%d",&board[i]);//這里和next數組統一也從0開始
int re = Find();
if(re == -1)printf("-1\n");
else printf("%d\n",re+1);//由於前面是從0開始而題中是從1開始所以這里加1
}

return 0;
}
``````

#### 注意！

© 2014-2022 ITdaan.com 联系我们： 