hiho1015(kmp+统计出现次数)

http://hihocoder.com/problemset/problem/1015

时隔多天再次温习了一下KMP

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 using namespace std;
 6 int Next[1000010];  //小写回编译错误
 7 void kmp_pre(char x[], int m)
 8 {
 9     int i,k;
10     Next[0] = -1;
11     k = -1;
12     i = 0;
13     while(i < m)
14     {
15         while(-1 != k && x[i] != x[k])
16             k = Next[k] ;
17         if(x[i + 1] == x[k + 1])
18             Next[++i] = Next[++k];
19         else
20             Next[++i] = ++k;
21     }
22 }
23 int kmp_Count(char x[], int m, char y[],int n)
24 {
25     int i,j;
26     int ans = 0;
27     kmp_pre(x,m);
28     i = j = 0;
29     while(i < n)
30     {
31         while(-1 != j && y[i] != x[j])
32             j = Next[j];
33         i++;
34         j++;
35         if(j >= m)
36         {
37             ans++;
38             j = Next[j];
39         }
40     }
41     return ans;
42 }
43 int main()
44 {
45     int n;
46     char t[1000000 + 10],p[1000000 + 10];
47     scanf("%d", &n);
48     while(n--)
49     {
50         scanf("%s%s", t,p);
51         int m = strlen(t);
52         int n = strlen(p);
53         printf("%d\n",kmp_Count(t,m,p,n));
54     }
55     return 0;
56 }
View Code

 

KMP讲解

http://www.cnblogs.com/tangzhengyue/p/4315393.html

posted @ 2015-12-28 20:16  zhaop  阅读(178)  评论(0编辑  收藏  举报