KMP(http://acm.hdu.edu.cn/showproblem.php?pid=1711)
http://acm.hdu.edu.cn/showproblem.php?pid=1711
#include<stdio.h> #include<math.h> #include<string.h> #include<stdlib.h> int a[1000010], b[10010], next[10010]; int n, m; void GetNext(int b[])//获得next数组 { int k = -1, j = 0; next[0] = -1; while(j < m) { if(k == -1 || b[j] == b[k])//b[k]表示前缀b[j]表示后缀 { j++; k++; if(b[j] != b[k]) next[j] = k; else next[j] = next[k]; } else k = next[k]; } } int KMP(int a[], int b[]) { int i = 0, j = 0; while(i < n && j < m) { if(j == -1 || a[i] == b[j])//j == -1或当前字符匹配成功,则i++,j++ { i++; j++; } else//j != -1 且当前字符匹配成功,b字符串向后移动j-next[j]位 j = next[j]; } if(j == m) return i - j + 1; return -1; } int main() { int t, i; 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(b); printf("%d\n", KMP(a, b)); } return 0; }