标签:style blog http os io for ar 2014
题意:就是要你来找出b数组在a数组中最先匹配的位置,如果没有则输出-1
思路:直接KMP算法(算法具体思想这位牛写的不错http://blog.csdn.net/v_july_v/article/details/7041827)
AC代码:
#include<cstdio> #include<cstring> #include<stdlib.h> #include<iostream> using namespace std; #define maxn 1000005 int b[10005]; int a[maxn]; int next[maxn]; int n,m; /*void GetNext() { next[0] = -1; int k=-1; int j=0; while(j<m) { if (k==-1||b[j]==b[k]) { ++k; ++j; next[j]=k; } else { k=next[k]; } } }*/ void GetNext() { next[0] = -1; int k=-1; int j=0; while (j<m) { if (k==-1||b[j]==b[k]) { ++j; ++k; if (b[j]!=b[k]) next[j] = k; else next[j] = next[k]; } else { k=next[k]; } } } int KmpSearch() { int i=0,j=0; while(i<n&& j <m) { if (j==-1||a[i]==b[j]) { i++; j++; } else j=next[j]; } if(j==m) return i-j+1; else return -1; } int main() { int i,j,t; scanf("%d",&t); while(t--) { scanf("%d %d",&n,&m); for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<m;i++) scanf("%d",&b[i]); GetNext(); printf("%d\n",KmpSearch()); } return 0; }
KMP算法的定义及KMP练手题 HDU 1711 Number Sequence (我的模板代码),布布扣,bubuko.com
KMP算法的定义及KMP练手题 HDU 1711 Number Sequence (我的模板代码)
标签:style blog http os io for ar 2014
原文地址:http://blog.csdn.net/u012313382/article/details/38520205