数据结构实验之串三: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
注意:1,唯一。2,数据10000000以上。
以下超时。
#include<stdio.h>
#include<string.h>
char str1[10000010], str2[10000010];
int next[10000010];
void get_next(char s[])
{
int j = 0, k = -1, len = strlen(s);
next[0] = 0;
while(j < len)
{
if(k == 1 || s[j] == s[k])
{
k++;
j++;
next[j] = k;
}
else
{
k = next[k];
}
}
/* for(i = 1; i < len; i++)
{
j = next[i-1];
while(j > 0 && s[j] != s[i])
{
j = next[j - 1];
}
if(s[i] == s[j])
{
next[i] = j + 1;
}
else
{
next[i] = 0;
}
}
*/
}
int KMP(char str1[], char str2[])
{
int i = 0, j = 0,sum = 0,l,r;
while(i < strlen(str1) )
{
if(str1[i] == str2[j])
{
i++;
j++;
}
else
{
if(j == 0)
{
i++;
}
else
{
j = next[j - 1];
}
}
if(j == strlen(str2)&&sum == 0)
{
sum++;
l = i - j + 1;
r = i;
j = 0;
}
else if(j == strlen(str2))
{
sum++;
j = 0;
}
}
// printf("%d\n",sum);
if(sum == 1) printf("%d %d\n",l ,r);
else printf("-1\n");
}
int main()
{
int n,m,i;
scanf("%d",&n);
for(i = 0; i < n; i++)
{
getchar();
scanf("%c",&str1[i]);
}
scanf("%d",&m);
for(i = 0; i < m; i++)
{
getchar();
scanf("%c",&str2[i]);
//getchar();
}
get_next(str2);
KMP(str1, str2);
return 0;
}
网友的码:
#include <stdio.h>
#include <string.h>
int nextval[1000005];
void getnextval(int s2[], int m){
int i = 0;
nextval[0] = -1;
int j = -1;
while(i < m){
if(j == -1||s2[i] == s2[j]){
i++;j++;
if(s2[i] != s2[j])
nextval[i] = j;
else
nextval[i] = nextval[j];
}
else
j = nextval[j];
}
}
int kmp(int s1[], int s2[], int n, int m, int x){
int i = x;
int j = 0;
while(i < n&&j < m){
if(j == -1||s1[i]==s2[j])
{
++i;
++j;
}
else
j= nextval[j];
}
if(j >= m)
return i-m+1;
else
return -1;
}
int main(){
int n, m, i;
int s1[1000005],s2[1000005];
scanf("%d", &n);
for(i=0; i<n; i++){
scanf("%d",&s1[i]);
}
scanf("%d",&m);
for(i=0; i<m; i++){
scanf("%d",&s2[i]);
}
getnextval(s2, m);
int x = kmp(s1, s2, n, m, 0);
if(x!=-1){
int t = kmp(s1, s2, n, m, x);
if(t == -1)
printf("%d %d\n", x, x+m-1);
else
printf("-1\n");
}
else
printf("-1\n");
return 0;
}