标签:
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 16335 Accepted Submission(s):
7198
#include<stdio.h> #include<string.h> const int MAXN = 1e6+7; int mumStr[MAXN], sonStr[MAXN]; int Next[MAXN]; void GetNext(int s[], int N, int next[]) { int i=0, j=-1; next[0] = -1; while(i < N) { if(j==-1 || s[i]==s[j]) next[++i] = ++j; else j = next[j]; } } int KMP(int mumStr[], int sonStr[], int Mn, int Sn) { int i=0, j=0; GetNext(sonStr, Sn, Next); while(i < Mn) { while(j==-1 || (mumStr[i]==sonStr[j]&&i<Mn&&j<Sn) ) i++, j++; if(j == Sn) return i-Sn+1; j = Next[j]; } return -1; } int main() { int T; scanf("%d", &T); while(T--) { int i, Mn, Sn; scanf("%d%d", &Mn, &Sn); for(i=0; i<Mn; i++) scanf("%d", &mumStr[i]); for(i=0; i<Sn; i++) scanf("%d", &sonStr[i]); printf("%d\n", KMP(mumStr, sonStr, Mn, Sn)); } return 0; }
标签:
原文地址:http://www.cnblogs.com/Loving140/p/4881121.html