KMP算法
View Code
#include<stdio.h> #include<string.h> const int N = 10010; char T[1000010], P[N]; int pi[N]; int ans; void COMPUTER_PREFIX_FUNCTION(){ int m = strlen(P), i, k; for(k = pi[0] = -1, i = 1; i < m; i++){ while(k > -1 && P[k+1] != P[i]) k = pi[k]; if(P[k+1] == P[i]) k++; pi[i] = k; } } void KMP_MATCHER(){ int i, n, m, k; n = strlen(T); m = strlen(P); for(k = -1, i = 0; i < n; i++){ while(k > -1 && P[k+1] != T[i]) k = pi[k]; if(P[k+1] == T[i]) k++; if(k == m-1){ ans ++; k = pi[k]; } } } int main(){ //freopen("data.in", "r", stdin); int n; scanf("%d", &n); while(n--) { scanf("%s %s", P, T); ans = 0; COMPUTER_PREFIX_FUNCTION(); KMP_MATCHER(); printf("%d\n", ans); } return 0; }