标签:hdu 1711 number sequence kmp 博客题解
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
6 -1
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <string> #include <map> #include <stack> #include <vector> #include <set> #include <queue> #pragma comment (linker,"/STACK:102400000,102400000") #define maxn 1000005 #define MAXN 2005 #define mod 1000000009 #define INF 0x3f3f3f3f #define pi acos(-1.0) #define eps 1e-6 typedef long long ll; using namespace std; int s[maxn],p[maxn],nextval[maxn]; int N,M; void get_nextval() { int i=0,j=-1; nextval[0]=-1; while (i<M) { 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]; } } int KMP() { int i=0,j=0; while (i<N&&j<M) { if (j==-1||s[i]==p[j]) { i++; j++; } else j=nextval[j]; } if (j==M) return i-M+1; else return -1; } int main() { int cas; scanf("%d",&cas); while (cas--) { scanf("%d%d",&N,&M); for (int i=0;i<N;i++) scanf("%d",&s[i]); for (int i=0;i<M;i++) scanf("%d",&p[i]); get_nextval(); int ans=KMP(); printf("%d\n",ans); } return 0; } /* 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 */
hdu 1711 Number Sequence KMP 基础题
标签:hdu 1711 number sequence kmp 博客题解
原文地址:http://blog.csdn.net/u014422052/article/details/40260619