题意:给你一个模式串和一个文本串,问你文本串中有多少个模式串

解题思路:裸的KMP,但是不适合july的第二种求next方法,个人还是偏向于第一种,

解题代码:

 1 // File Name: getnext.cpp
 2 // Author: darkdream
 3 // Created Time: 2014年09月09日 星期二 22时35分02秒
 4 
 5 #include<vector>
 6 #include<list>
 7 #include<map>
 8 #include<set>
 9 #include<deque>
10 #include<stack>
11 #include<bitset>
12 #include<algorithm>
13 #include<functional>
14 #include<numeric>
15 #include<utility>
16 #include<sstream>
17 #include<iostream>
18 #include<iomanip>
19 #include<cstdio>
20 #include<cmath>
21 #include<cstdlib>
22 #include<cstring>
23 #include<ctime>
24 #define LL long long
25 
26 using namespace std;
27 char str[1000005];
28 char str1[1000005];
29 int next[1000005];
30 void getnext()
31 {
32    int len = strlen(str1);
33    next[0] = -1; 
34    int k = -1;
35    int j = 0 ; 
36    while(j <= len - 1)
37    {
38       if(k == -1 || str1[j] == str1[k])
39       {
40          ++j; 
41          ++k;
42              next[j] = k ;
43       }
44       else {
45          k = next[k];
46       }
47    }
48 }
49 int kmp()
50 {
51   int sum = 0 ; 
52   int len = strlen(str);
53   int len1 = strlen(str1);
54   int i = 0 ; 
55   int j = 0 ;
56   getnext();
57   while(i < len )
58   {
59      if(j ==  -1 || str[i] == str1[j])
60      {
61         i ++ ;
62         j ++ ;
63      }else{
64        j = next[j];
65      }
66      if(j == len1 )
67      {
68         sum ++ ; 
69      }
70   }
71   printf("%d\n",sum);
72 }
73 int main(){
74     int t; 
75     scanf("%d",&t);
76     while(t--)
77     { 
78         scanf("%s",str1);
79         scanf("%s",str);
80         kmp(); 
81     }
82     return 0;
83 }
View Code

 

posted on 2014-09-10 10:09  dark_dream  阅读(130)  评论(0编辑  收藏  举报