KMP算法:
先简单说一下kmp这个匹配算法,它是将一串(子串)字符与另一串(母串)字符相比较,而后在母串中找到和子串相同的串,那我们怎么寻找这个串呢?如果暴力跑,那么我们试想一下,假如母串长度为 n ,子串长度为m,暴力之下,复杂度为O(n*m),但kmp降到O(n+m),厉害吧!
话不多说,看代码吧。。。。(一种写法,不一般的写法)
char s1[MAXN];//子串
char s2[MAXN];//母串
int len=strlen(s1);void getnext()
{
int i=0,j=-1;
next[0]=-1;
while (i<m)
{
if (j==-1||s1[i]==s1[j])
{
i++;
j++;
if (s1[i]!=s1[j])
next[i]=j;
else
next[i]=next[j];
}
else
j=next[j];
}
}
这里我们先获取一个next[MAXN]的数组,这个数组很强大,它是用来记录前面匹配数的,当失配时,则可以回到上一次失配时的地方,如果可以继续匹配,则不需要回到开始的 next[0] (除非返回时一直失配)的位置重新匹配,这样就降低复杂度;所以这个next[MAXN]数组在具有重要位置。。。
例题:
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
ac代码:
#include<stdio.h>
const int MAXN=1e6+10;
int next[MAXN];
int s1[MAXN];
int s2[MAXN];
int m,n;
void getnext() {
int i=0,j=-1;
next[0]=-1;
while (i<m) {
if (j==-1||s1[i]==s1[j]) {
i++;
j++;
if (s1[i]!=s1[j])
next[i]=j;
else
next[i]=next[j];
} else
j=next[j];
}
}
void kmp() {
int i=0,j=0;
while (i<n&&j<m) {
if (j==-1||s2[i]==s1[j]) {
i++;
j++;
} else
j=next[j];
}
if (j==m)
printf("%d\n",i-m+1);
else
printf("-1\n");
}
int main() {
int t;
scanf("%d",&t);
while (t--) {
scanf("%d%d",&n,&m);
for (int i=0; i<n; i++)
scanf("%d",&s2[i]);
for (int i=0; i<m; i++)
scanf("%d",&s1[i]);
getnext();
kmp();
}
return 0;
}
简洁中的美感。。。。