KMP基础
这是个KMP算法的裸题,没什么好说的主要是为了储备算法,以后好看,实名安利一波哔哩哔哩,里面大佬讲的真的都挺好的,再结合一下博客应该可以比较直观的对KMP有大概认识。
数据结构实验之串三:KMP应用 :这题本来可以直接while循环嵌套写的,不过为了突出KMP的各个部分特地分开写了。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 1000005
int next[N], a[N], s[N];
void get_next(int *s, int n)
{
int i = 0, j = -1;
next[i] = -1;
while(i < n)
{
if(j == -1 || s[i] == s[j])
{
i++;
j++;
if(s[i] != s[j])
next[i] = j;
else
next[i] = next[j];
}
else
j = next[j];
}
}
int Kmp(int n, int m, int ii, int jj)
{
int i = ii, j = jj;
while(i < n && j < m)
{
if(a[i] == s[j] || j == -1)
{
i++;
j++;
}
else
j = next[j];
}
if(j >= m)
return i - m + 1;
else
return -1;
}
int main()
{
int n, m, i;
while(~scanf("%d", &n))
{
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
scanf("%d", &m);
for(i = 0; i < m; i++)
{
scanf("%d", &s[i]);
}
get_next(s, m);
int c = Kmp(n, m, 0, 0);
if(c != -1)
{
int b = Kmp(n, m, c + m - 1, next[m]);
if(b == -1)
printf("%d %d
", c, c + m - 1);
else
printf("-1
");
}
else
printf("-1
");
}
return 0;
}
/***************************************************
User name: rj180229
Result: Accepted
Take time: 188ms
Take Memory: 780KB
Submit time: 2018-12-18 21:12:02
****************************************************/