数据结构实验之串三:KMP应用
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
有n个小朋友,每个小朋友手里有一些糖块,现在这些小朋友排成一排,编号是由1到n。现在给出m个数,能不能唯一的确定一对值l和r(l <= r),使得这m个数刚好是第l个小朋友到第r个小朋友手里的糖块数?
Input
首先输入一个整数n,代表有n个小朋友。下一行输入n个数,分别代表每个小朋友手里糖的数量。
之后再输入一个整数m,代表下面有m个数。下一行输入这m个数。
Output
如果能唯一的确定一对l,r的值,那么输出这两个值,否则输出-1
Example Input
5 1 2 3 4 5 3 2 3 4
Example Output
2 4
Hint
Author
windream
</pre><pre code_snippet_id="1949471" snippet_file_name="blog_20161026_1_9327761" name="code" class="cpp">
<pre name="code" class="cpp">#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int a[1000000+5], b[1000000+5];
int next[1000000+5], n, m;
void getnext() {
next[0]=-1;
int i=0, j=-1;
while(i<n) {
if(j==-1||b[i]==b[j]) {
i++;
j++;
next[i]=j;
}
else j=next[j];
}
}
void kmp() {
getnext();
int i=0, j=0;
while(i<n&&j<m) {
if(a[i]==b[j]||j==-1) {
i++;
j++;
}
else j=next[j];
}
if(j>=m) {
int x=i;
j=0;
while(i<n&&j<m) {
if(a[i]==b[j]||j==-1) {
i++;
j++;
}
else j=next[j];
}
if(j>=m) printf("-1\n");
else printf("%d %d\n", x-m+1, x);
}
else printf("-1\n");
}
int main() {
scanf("%d", &n);
for(int i=0;i<n;i++)
scanf("%d", &a[i]);
scanf("%d", &m);
for(int i=0;i<m;i++)
scanf("%d", &b[i]);
kmp();
return 0;
}