kuangbin专题十六 KMP&&扩展KMP HDU1711 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.
InputThe 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].

OutputFor 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 首先是预处理Next数组,初始化Next[0]=-1,j=-1 然后从i=0开始,如果j!=-1&&不匹配,j=Next[j]。否则判断p[++i]==p[++j],如果相等,直接让Next[i]=Next[j],不等的话,让Next[i]=j; 然后在主串里匹配。i=0,j=0; j!=-1&&不匹配, j=Next[j]。否则i++,j++
 #include<stdio.h>
#include<string.h>
int Next[],t[],p[];//模式串对应的Next
int n,m,_; void prekmp() {//预处理Next数组
int i,j;
j=Next[]=-;
i=;
while(i<m) {
while(j!=-&&p[i]!=p[j]) j=Next[j];
if(p[++i]==p[++j]) Next[i]=Next[j];//会快一点 博客体现了这一点
else Next[i]=j;
}
} int kmp() {//查找在主串的位置
int i=,j=;
prekmp();
while(i<n&&j<m) {
while(j!=-&&t[i]!=p[j]) j=Next[j];
i++;j++;
}
if(j==m) return i-m+;
else return -;
} int main() {
for(scanf("%d",&_);_;_--) {
scanf("%d%d",&n,&m);
for(int i=;i<n;i++) {
scanf("%d",&t[i]);
}
for(int i=;i<m;i++) {
scanf("%d",&p[i]);
}
int ans=kmp();
printf("%d\n",ans);
}
}

上一篇:kuangbin专题十六 KMP&&扩展KMP HDU1238 Substrings


下一篇:G - A+B for Input-Output Practice (VI)