kmp模版题 hdu1686

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 
 5 using namespace std;
 6 
 7 char s[1000010];
 8 char t[10010];
 9 int next1[10010];
10 int m,n;
11 
12 void getnext()
13 {
14     next1[0]=-1;
15     int i=0;
16     int j=-1;
17     while(i<m)
18     {
19         while(j!=-1&&t[i]!=t[j])
20         {
21             j=next1[j];
22         }
23         next1[++i]=++j;
24     }
25 }
26 
27 int kmp()
28 {
29     int ans=0;
30     getnext();
31     int i=0;
32     int j=0;
33     while(i<n)
34     {
35         while(j!=-1&&s[i]!=t[j])
36         {
37             j=next1[j];
38         }
39         i++;
40         j++;
41         if(j>=m)
42         {
43             ans++;
44             j=next1[j];
45         }
46     }
47     return ans;
48 }
49 
50 int main()
51 {
52     int T;
53     scanf("%d",&T);
54     while(T--)
55     {
56         scanf("%s",&t);
57         scanf("%s",&s);
58         n=strlen(s);
59         m=strlen(t);
60         cout<<kmp()<<endl;
61     }
62     return 0;
63 }
View Code

 

posted @ 2015-10-06 12:50  相儒以沫  阅读(128)  评论(0编辑  收藏  举报