http://acm.hdu.edu.cn/showproblem.php?pid=1711
题意:从s串中如果能找出p串,则输出p串在s串的位置(两个串下标都从1开始)
KMP模板题。。。。
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <queue>
#include <stack>
#include <math.h>
#include <algorithm>
using namespace std;
int s[1000010],p[10010];
int nextval[10010];
int num1,num2;
/*
5
13 10
1 2 3 1 4 5 8 7 2 1 4 7 6
1 2 1 2 3 1 2 1 2 9
-1 0 0 1 2 0 1 2 3 4 0
-1 0 -1 0 2 -1 0 -1 0 4 0
*/
void getnext(const int*p){
int i = 0, j = -1;
nextval[0] = -1;
while(i != num2){
if(j == -1 || p[i] == p[j]) nextval[++i] = ++j;
else j = nextval[j];
}
}
int KMP(const int *s,const int *p){
int i=0,j=0;
while(i!=num1&&j!=num2){
if(s[i]!=p[j]){
if(nextval[j]==-1) i++,j=0;
else j=nextval[j];
}else i++,j++;
}//while
if(j==num2) return i-j+1;
return -1;
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d",&num1,&num2);
for(int i=0;i<num1;i++) scanf("%d",&s[i]);
for(int i=0;i<num2;i++) scanf("%d",&p[i]);
getnext(p);
int ans=KMP(s,p);
printf("%d\n",ans);
}//while
return 0;
}
稍作优化:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <queue>
#include <stack>
#include <math.h>
#include <algorithm>
using namespace std;
int s[1000010],p[10010];
int nextval[10010];
int num1,num2;
void getnext(const int *p){
int i=0,j=-1;
nextval[0]=-1;
while(i!=num2){
if(j==-1||p[i]==p[j]){
i++;j++;
if(p[i]!=p[j]) nextval[i]=j;
else nextval[i]=nextval[j];
}else j=nextval[j];
}//while
}
int KMP(const int *s,const int *p){
int i=0,j=0;
while(i!=num1&&j!=num2){
if(s[i]!=p[j]){
if(nextval[j]==-1) i++,j=0;
else j=nextval[j];
}else i++,j++;
}//while
if(j==num2) return i-j+1;
return -1;
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d",&num1,&num2);
for(int i=0;i<num1;i++) scanf("%d",&s[i]);
for(int i=0;i<num2;i++) scanf("%d",&p[i]);
getnext(p);
int ans=KMP(s,p);
printf("%d\n",ans);
}//while
return 0;
}