【KMP應用】HDU 1711
阿新 • • 發佈:2019-01-27
簡單的KMP,不解釋。
#include <map> #include <set> #include <list> #include <queue> #include <deque> #include <stack> #include <string> #include <time.h> #include <cstdio> #include <math.h> #include <iomanip> #include <cstdlib> #include <limits.h> #include <string.h> #include <iostream> #include <fstream> #include <algorithm> using namespace std; #define LL long long #define MIN INT_MIN #define MAX INT_MAX #define PI acos(-1.0) #define FRE freopen("input.txt","r",stdin) #define FF freopen("output.txt","w",stdout) #define N 50005 int a[1000005],b[10005]; int p[10005]; int n,m; void gao () { int i,j = 0; p[1] = 0; for (i = 2; i <= m; i++) { while (j > 0 && b[j+1] != b[i]) { j = p[j]; } if (b[i] == b[j+1]) j++; p[i] = j; } } void kmp () { int i,j = 0; for (i = 1; i <= n; i++) { while (j > 0 && b[j+1] != a[i]) { j = p[j]; } if (b[j+1] == a[i]) j++; if (j == m) { printf("%d\n",i - m +1 ); return ; } } printf("%d\n",-1); } int main () { int t; scanf("%d",&t); while (t--) { scanf("%d%d",&n,&m); int i,j; for (i = 1; i <= n ;i++) scanf("%d",&a[i]); for (i = 1; i <= m; i++) scanf("%d",&b[i]); gao(); kmp(); } return 0; }