HDOJ_1711_KMP 入门
/* HDOJ_1711_KMP 求匹配位置
*
* I really like this KMP in door
*
* Author : a_clay 2014/05/06
*/
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <algorithm>
#include <cmath>
#define Bug cout << "here\n";
using namespace std;
const int N = 1000005;
const int M = 10005;
int s[N];
int t[M];
int next[M];
void get_next(int len) {
int i, j;
i = 0;
j = -1;
next[0] = -1;
while (i < len - 1) {
if (j == -1 || t[i] == t[j]) {
i++; j++; next[i] = j;
}
else {
j = next[j]; // 核心中的核心,KMP中的KMP。
}
}
}
int kmp(int sl, int tl) {
int i, j;
i = 0;
j = 0;
while (i < sl && j < tl) {
if (j == -1 || s[i] == t[j]) { //j == -1 是第一个就没有匹配上,类似于传统方法,i要向后移动,因为-1的巧妙设置,所以j依然很好的移动,i 还是从第一位 开始从 j==0比较
i++; j++;
}
else { j = next[j];}
}
if (j == tl) {
return i-j+1;
}
else return -1;
}
// abcabcababcabcabdef
// abcabcabd
int main() {
int T, n, m, ans;
cin >> T;
while (T--) {
cin >> n >> m;
int i;
for (i = 0; i < n; i++) {
scanf("%d", s+i);
}
for (i = 0; i < m; i++) {
scanf("%d", t+i);
}
get_next(m);
ans = kmp(n, m);
cout << ans << endl;
}
return 0;
}