大意:kmp
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 6 const int maxn = 1000005; 7 8 int next[maxn]; 9 10 void get(char *s) { 11 int l = strlen(s); 12 int j = 0, k = -1; 13 next[0] = -1; 14 while(j < l) { 15 if(k == -1 || s[j] == s[k]) { 16 next[++j] = ++k; 17 } else { 18 k = next[k]; 19 } 20 } 21 } 22 23 int kmp(char *s1, char *s2) { 24 int l1 = strlen(s1), l2 = strlen(s2); 25 int i = 0, j = 0; 26 int sum = 0; 27 get(s2); 28 while(i < l1 && j < l2) { 29 if(j == -1 || s1[i] == s2[j]) { 30 i++; j++; 31 } else { 32 j = next[j]; 33 } 34 if(j == l2) { 35 sum++; 36 j = next[j]; 37 } 38 } 39 return sum; 40 } 41 42 char s1[maxn], s2[maxn]; 43 int main() { 44 int t; 45 scanf("%d",&t); 46 while(t--) { 47 scanf("%s",s1); 48 scanf("%s",s2); 49 // printf("%s %s ",s1, s2); 50 printf("%d ", kmp(s2,s1)); 51 } 52 }