hdu1711(kmp)
来源:互联网 发布:淘宝假冒伪劣无需退货 编辑:程序博客网 时间:2024/05/20 18:15
#include <iostream>#include <cstdio>#include <string.h>using namespace std;const int M = 10010;const int MAX = 1000010;int next[M];int a[MAX];int b[M];int n, m;void get_next(int len){ int i, j; i = 0; j = -1; next[0] = -1; while(i < len-1){ if(j == -1 || b[i] == b[j]){ i++; j++; next[i] = j; } else{ j = next[j]; } }}int kmp(){ int i, j; i = 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; } return -1;}int main(){ int count; scanf("%d", &count); for(int k = 0; k < count; k++) { scanf("%d%d", &n, &m); for(int i = 0; i < n; i++) { scanf("%d", a+i); } for(int i = 0; i < m; i++){ scanf("%d", b+i); } get_next(m); int ans = kmp(); printf("%d\n", ans); } return 0;}