POJ 3461 Oulipo KMP演算法
阿新 • • 發佈:2020-11-22
#include<iostream> #include<cstring> using namespace std; int N; int nex[10010]; char s[1000010]; char p[10010]; void GetNext() { nex[0] = -1; int i = 0; int j = -1; int len_p = strlen(p); while(i < len_p) { if(j == -1 || p[i] == p[j]) { i++; j++; nex[i] = j; } else j = nex[j]; } } int KMP() { int i = 0, j = 0; int res = 0; int len_s = strlen(s), len_p = strlen(p); while(i < len_s) { if(j == -1 || s[i] == p[j]) { if(j == len_p-1) { res++; j = nex[j]; } else { i++; j++; } } else j = nex[j]; } return res; } int main() { scanf("%d", &N); while(N--) { scanf("%s", p); scanf("%s", s); GetNext(); printf("%d\n", KMP()); } system("pause"); return 0; }