Given two sequences of numbers : a[1], a[2], ...... , a[N], and b[1], b[2], ...... , b[M] (1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make a[K] = b[1], a[K + 1] = b[2], ...... , a[K + M - 1] = b[M]. If there are more than one K exist, output the smallest one.
题意:给出一个待匹配串和一个模式串,问模式串在哪个位置被匹配,输出最小位置,若没有匹配,输出-1
KMP裸题
1 #include<stdio.h>
2 #include<string.h>
3
4 int s[1000005],t[10005];
5 int p[10005];
6
7 int main(){
8 int T;
9 scanf("%d",&T);
10 while(T--){
11 int n,m;
12 scanf("%d%d",&n,&m);
13 for(int i=0;i<n;++i)scanf("%d",&s[i]);
14 for(int i=0;i<m;++i)scanf("%d",&t[i]);
15 int i,j,ans=-1;
16 p[0]=p[1]=0;
17 for(i=1;i<m;++i){
18 j=p[i];
19 while(j&&t[i]!=t[j])j=p[j];
20 p[i+1]=t[i]==t[j]?j+1:0;
21 }
22 j=0;
23 for(i=0;i<n;++i){
24 while(j&&s[i]!=t[j])j=p[j];
25 if(s[i]==t[j])j++;
26 if(j==m){
27 ans=i-m+2;
28 break;
29 }
30 }
31 printf("%d
",ans);
32 }
33 return 0;
34 }