Input
Output
Sample Input
2 13 5 1 2 1 2 3 1 2 3 1 3 2 1 2 1 2 3 1 3 13 5 1 2 1 2 3 1 2 3 1 3 2 1 2 1 2 3 2 1
Sample Output
6 -1
#include<stdio.h> #include<algorithm> #include<string.h> using namespace std; int next[10007]; int x[1000077]; int y[1000077]; int main() { int n; scanf("%d",&n); while(n--) { int a,b,i; scanf("%d%d",&a,&b); for(i=0;i<a;i++) { scanf("%d",&x[i]); } for(i=0;i<b;i++) { scanf("%d",&y[i]); } next[0]=next[1]=0; for(i=1;i<b;i++) { int j=next[i]; while(j&&y[i]!=y[j]) { j=next[j]; } next[i+1]=y[i]==y[j]?j+1:0; } int j=0,flag=0; for(i=0;i<a;i++){ while(j&&x[i] != y[j])j = next[j]; if(x[i] == y[j])j++; if(j == b){flag = 1;break;} } if(flag)printf("%d\n",i-b+2); else printf("-1\n"); } }
#include<stdio.h> #include<string.h> using namespace std; int next[10010]; int aa[1000010]; void getNext(int *bb,int b){ next [0] = next[1] = 0; for(int i=1;i<b;i++){ int j = next[i]; while(j&&bb[i]!=bb[j])j = next[j]; next[i+1] = bb[i] == bb[j]?j+1:0; } } int main(){ int n,a,b,bb[10010]; scanf("%d",&n); while(n--){ int flag = 0; scanf("%d%d",&a,&b); for(int i=0;i<a;i++){ scanf("%d",&aa[i]); } for(int i=0;i<b;i++){ scanf("%d",&bb[i]); } getNext(bb,b); int j =0; int i; for(i=0;i<a;i++){ while(j&&aa[i] != bb[j])j = next[j]; if(aa[i] == bb[j])j++; if(j == b){flag = 1;break;} } if(flag)printf("%d\n",i-b+2); else printf("-1\n"); } }
SDJZU_新生_字符串匹配(KMP)_A - Number Sequence
原文地址:http://blog.csdn.net/floating_life/article/details/43272243