数据结构实验之串三:KMP应用
Time Limit: 1000 ms
Memory Limit: 65536 KiB
Problem Description
有n个小朋友,每个小朋友手里有一些糖块,现在这些小朋友排成一排,编号是由1到n。现在给出m个数,能不能唯一的确定一对值l和r(l <= r),使得这m个数刚好是第l个小朋友到第r个小朋友手里的糖块数?
Input
首先输入一个整数n,代表有n个小朋友。下一行输入n个数,分别代表每个小朋友手里糖的数量。
之后再输入一个整数m,代表下面有m个数。下一行输入这m个数。
Output
如果能唯一的确定一对l,r的值,那么输出这两个值,否则输出-1
Sample Input
5 1 2 3 4 5 3 2 3 4
Sample Output
2 4
Hint
Source
windream
解题思路:这个题肯定是要用KMP的,不过如何判断只出现一次,这里看到网上各位大佬的用法还是挺巧妙的。在KMP算法中如果匹配到目标字串,则跳出循环,这里我们可以返回目标子串在原始串中的起始位置,然后我们从目标串在原始串中的终止位置再进行一次KMP算法,如果剩下的串中还能匹配到,说明不止出现一次,说明不符合。反之则符合。
AC代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10000000
///反过头来还需要仔细看一下KMP算法的实现,虽然这个代码不是复制的,但还是看着别人的一点一点敲出来的
///
int a[N], b[N];
int next[N];
int n, m;
void get_next() ///生成待匹配数组的next数组
{
int i, j;
next[0] = -1;
for(j = 1; j<=m; j++)
{
i = next[j-1];
while(b[j] != b[i+1] && i>=0)
{
i = next[i];
}
if(b[j] == b[i+1])
{
next[j] = i+1;
}
else
{
next[j] = -1;
}
}
}
int KMP(int a[],int b[]) ///KMP算法
{
get_next();
int p, s;
p = 0, s = 0;
while(p < m && s < n)
{
if(a[s] == b[p])
{
s++;
p++;
}
else
{
if(p == 0)
{
s++;
}
else
{
p = next[p-1]+1;
}
}
}
if(p < m)
{
return -1;
}
else
{
return s-m+1;
}
}
int main()
{
int i, k, t;
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", &b[i]);
}
k = KMP(a, b);
if(k != -1)
{
t = KMP(a+k, b);
if(t == -1)
{
printf("%d %d\n", k, k+m-1);
}
else
{
printf("%d\n",-1);
}
}
else
{
printf("%d\n",-1);
}
}
return 0;
}