数据结构实验之串三:KMP应用
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
有n个小朋友,每个小朋友手里有一些糖块,现在这些小朋友排成一排,编号是由1到n。现在给出m个数,能不能唯一的确定一对值l和r(l <= r),使得这m个数刚好是第l个小朋友到第r个小朋友手里的糖块数?
输入
首先输入一个整数n,代表有n个小朋友。(0
输出
如果能唯一的确定一对l,r的值,那么输出这两个值,否则输出-1
示例输入
5 1 2 3 4 5 3 2 3 4
示例输出
2 4
提示
来源
windream
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;
int n, m;
int next[1000100];
int s[1000010], t[1000010];
void get_next(int t[], int next[])
{
int i=1;
next[1] = 0;
int j = 0;
while(i < m)
{
if(j == 0 || t[i] == t[j])
{
++i;
++j;
next[i] = j;
}
else
j = next[j];
}
}
void KMP(int n, int m)
{
int pos=1;
int k = 1;
int f=0, h;
while(pos <= n&&k <= m)
{
if(k == 0 || s[pos] == t[k])
{
++pos;
++k;
}
else
{
k = next[k];
}
if(k > m)
{
k = 1;
f++;
if(f == 1)
{
// d = 1;
h = pos;
}
}
}
if(f == 1)
printf("%d %d\n", h-m, h-1);
else
printf("-1\n");
}
int main()
{
int n, m;
scanf("%d", &n);
for(int i = 1; i <= n; i++)
scanf("%d", &s[i]);
scanf("%d", &m);
for(int j = 1; j <= m; j++)
scanf("%d", &t[j]);
get_next(t, next);
KMP(n, m);
return 0;
}