首页 > 其他 > 详细

hdu 1686 KMP模板

时间:2015-08-03 16:23:51      阅读:148      评论:0      收藏:0      [点我收藏+]
 1 //    hdu 1686 KMP模板
 2 
 3 //    没啥好说的,KMP裸题,这里是MP模板
 4 
 5 #include <cstdio>
 6 #include <iostream>
 7 #include <cstring>
 8 #include <algorithm>
 9 
10 using namespace std;
11 
12 const int MAX_N = 1000008;
13 const int MAX_M = 10008;
14 char T[MAX_N];
15 char p[MAX_M];
16 int f[MAX_M];
17 int n,m;
18 
19 void getfail(){
20     f[0] = f[1] = 0;
21     for (int i=1;i<m;i++){
22         int j = f[i];
23         while(j && p[i]!=p[j])
24             j = f[j];
25         f[i+1] = (p[i]==p[j]) ? j + 1 : 0;
26     }
27 }
28 
29 int cmp(){
30     int cnt = 0;
31     int j = 0;
32     for (int i=0;i<n;i++){
33         while(j && T[i] != p[j])
34             j = f[j];
35         if (T[i] == p[j])
36             j++;
37         if (j==m){
38             cnt++;
39         }
40     }
41     return cnt;
42 }
43 
44 int KMP(){
45     getfail();
46     return cmp();
47 }
48 
49 void input(){
50     scanf("%s%s",p,T);
51     n = strlen(T);
52     m = strlen(p);
53     printf("%d\n",KMP());
54 }
55 
56 int main(){
57     int t;
58     //freopen("1.txt","r",stdin);
59     scanf("%d",&t);
60     while(t--){
61         input();
62     }
63 }

 

hdu 1686 KMP模板

原文:http://www.cnblogs.com/KingJourney/p/4699564.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!