链接:点击打开链接(终于找到了按钮了)
先放两个大牛写的kmp算法详解
Problem 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函数:
kmp函数中,实际上是母串没有动,子串一直在动,那是移动到哪里呢?
代码:
//最长的前缀=后缀的长度
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<string>
#include<string.h>
#include<cstring>
#include<set>
#include<queue>
#include<stack>
#include<vector>
#include<functional>
#include<map>
using namespace std;
const int maxn = 1000005;
const int maxm = 10005;
const int INF = (int)1e9;
int a[maxn], b[maxm];
int t, n, m, k;
//根据已知的前j位推测第j + 1位
//特殊情况是k为-1时,不能继续递归了,此时next[j + 1]应该等于0,即把j回退到首位。
void getnext(int b[maxn], int next[maxm]) {
int j = 0, k = -1;
next[0] = -1;
while (j < m - 1) {//m是字符串长度
if (k == -1 || b[j] == b[k]) {
j++;
k++;
next[j] = k;
}
else
k = next[k];
}
}
void kmp(int a[maxn], int b[maxn]) {
int next[maxm];
int i = 0, j = 0;
getnext(b, next);
while (i < n) {
if (j == -1 || a[i] == b[j]) {//母串不动,子串移动
j++;
i++;
}
else {
// i不需要回溯了
// i = i - j + 1;
j = next[j];
}
if (j == m) {
printf("%d\n", i - m + 1);//母串的位置减去子串的长度+1
return;
}
}
printf("-1\n");
}
int main()
{
scanf("%d", &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]);
kmp(a, b);
}
//system("pause");
return 0;
}