数据结构实验之串三:KMP应用
Time Limit: 1000MS Memory limit: 65536K
题目描述
输入
输出
示例输入
5 1 2 3 4 5 3 2 3 4
示例输出
2 4
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int string1[1000000],string2[1000000];
int next[1000000];
void get_next(int len)
{
int i=0,j=-1;
next[0] = -1;
while(i<len)
{
if(j==-1 || string2[i]==string2[j])
{
i++;
j++;
next[i] = j;
}
else
{
j = next[j];
}
}
}
int Index_KMP(int x,int y,int pos)
{
int i=pos,j=0;
get_next(y);
while(i<x && j<y)
{
if(j==-1 || string1[i]==string2[j]) //j=-1
{
i++;
j++;
}
else
{
j = next[j];
}
}
if(j==y)
{
return i-j+1;
}
else
{
return -1;
}
}
int main()
{
int n,i,m,x;
while(scanf("%d",&n)!=EOF)
{
for(i=0;i<n;i++)
{
scanf("%d",&string1[i]);
}
scanf("%d",&m);
for(i=0;i<m;i++)
{
scanf("%d",&string2[i]);
}
x = Index_KMP(n,m,0);//找到模式串的在主串中的位置
if(x!=-1)
{
//此题要唯一确定一对l,r值;理解为确定唯一的子串,即模式串在主串中只出现一次,然后输出匹配模式串在主串中的首位置和末位置
int t = Index_KMP(n,m,x+m-1);
if(t!=-1)
{
printf("-1\n");
}
else
{
printf("%d %d\n",x,x+m-1);
}
}
else
{
printf("-1\n");
}
}
return 0;
}