hihoCoder 1015 KMP算法

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

因为kmp算法只预处理b串,因而适合求解,给定一个串和一群不同的a串,问b是那些a串的子串.

或者查找模式串在原串出现了几次.

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cmath>
 4 #include <vector>
 5 #include <cstring>
 6 #include <string>
 7 #include <algorithm>
 8 #include <string>
 9 #include <set>
10 #include <functional>
11 #include <numeric>
12 #include <sstream>
13 #include <stack>
14 #include <map>
15 #include <queue>
16 #pragma comment(linker, "/STACK:102400000,102400000")
17 #define CL(arr, val)    memset(arr, val, sizeof(arr))
18 
19 #define ll long long
20 #define inf 0x7f7f7f7f
21 #define lc l,m,rt<<1
22 #define rc m + 1,r,rt<<1|1
23 #define pi acos(-1.0)
24 
25 #define L(x)    (x) << 1
26 #define R(x)    (x) << 1 | 1
27 #define MID(l, r)   (l + r) >> 1
28 #define Min(x, y)   (x) < (y) ? (x) : (y)
29 #define Max(x, y)   (x) < (y) ? (y) : (x)
30 #define E(x)        (1 << (x))
31 #define iabs(x)     (x) < 0 ? -(x) : (x)
32 #define OUT(x)  printf("%I64d\n", x)
33 #define lowbit(x)   (x)&(-x)
34 #define Read()  freopen("a.txt", "r", stdin)
35 #define Write() freopen("b.txt", "w", stdout);
36 #define maxn 1000000000
37 #define N 2510
38 #define mod 1000000000
39 using namespace std;
40 
41 int p[10010];
42 char s1[10010],s2[1000010];
43 int n,m;
44 void next(int m)
45 {
46     int j=0;
47     p[1]=0;
48     for(int i=2;i<=m;i++)
49     {
50         while(j>0&&(s1[j+1]!=s1[i])) j=p[j];
51         if(s1[j+1]==s1[i]) j+=1;
52         p[i]=j;
53         //printf("%d\n",p[i]);
54     }
55 }
56 
57 int kmp(int n)
58 {
59     int j=0,k=0;
60     for(int i=1;i<=n;i++)
61     {
62         while(j>0&&s1[j+1]!=s2[i]) j=p[j];
63         if(s1[j+1]==s2[i]) j=j+1;
64         if(j==m)
65         {
66             k++;
67             j=p[j];
68         }
69         //printf("%d\n",j);
70     }
71     return k;
72 }
73 int main()
74 {
75    // freopen("a.txt","r",stdin);
76     int k;
77     scanf("%d",&k);
78     for(int i=0;i<k;i++)
79     {
80         scanf("%s",s1+1);
81         scanf("%s",s2+1);
82         m=strlen(s1+1);
83         //printf("%d\n",m);
84         next(m);
85         n=strlen(s2+1);
86         printf("%d\n",kmp(n));
87     }
88     return 0;
89 }

 

posted @ 2015-06-16 12:04  NowAndForever  阅读(244)  评论(0编辑  收藏  举报