题目链接:点击打开链接
数据结构实验之串三: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
科科科,好魔性,竟然数组小两个0 就WA了。。。
代码实现:
数组从0开始:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
int a[10010000],b[10010000];///好魔性,为什么数组小两个零就WA
int next[10010000],n,m;
void Get_next()
{
next[0] = -1;
int i = 0,j = -1;
while(i < m)
{
if(j == -1||b[i] == b[j])
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
}
int next_KMP(int a[],int b[],int c)
{
Get_next();
int i = c,j = 0;
while(i < n&&j < m)
{
if(j == -1||a[i] == b[j])
{
i++;
j++;
}
else
j = next[j];
}
if(j >= m)
return i - m + 1;
return -1;
}
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]);
int k = next_KMP(a,b,0);///判断两次,保证只有唯一的一组
if(k != -1)
{
int t = next_KMP(a,b,k);///不能从k+m-1开始,
///n=5,2 3 2 3 2,m=3,2 3 2,wa
if(t == -1)///第二次查找不存在
printf("%d %d\n",k,k+m-1);///输出
else
printf("-1\n");
}
else
printf("-1\n");
return 0;
}
数组从1开始:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
int n,m;
int a[100100100],b[100100100];
int next[100100100];
void Get_next()
{
int i = 1,j = 0;
next[1] = 0;
while(i <= m)
{
if(j == 0||b[i] == b[j])
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
}
int next_KMP(int a[],int b[])
{
Get_next();
int i = 1,j = 1;
while(i <= n&&j <= m)
{
if(j == 0||a[i] == b[j])
{
i++;
j++;
}
else
j = next[j];
}
if(j > m)
return i-m;
else
return -1;
}
int main()
{
scanf("%d",&n);
for(int i = 1;i <= n;i++)
scanf("%d",&a[i]);
scanf("%d",&m);
for(int i = 1;i <= m;i++)
scanf("%d",&b[i]);
int k = next_KMP(a,b);
if(k != -1)
{
int t = next_KMP(a+k,b);
if(t == -1)
printf("%d %d\n",k,k+m-1);
else
printf("-1\n");
}
else
printf("-1\n");
return 0;
}