Substring Frequency (KMP)

Substring Frequency

Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%lld & %llu

Submit Status Practice LightOJ 1255

Description

A string is a finite sequence of symbols that are chosen from an alphabet. In this problem you are given two non-empty strings A and B, both contain lower case English alphabets. You have to find the number of times B occurs as a substring of A.

Input

Input starts with an integer T (≤ 5), denoting the number of test cases.

Each case starts with two lines. First line contains A and second line contains B. You can assume than 1 ≤ length(A), length(B) ≤ 106.

Output

For each case, print the case number and the number of times B occurs as a substring of A.

Sample Input

4

axbyczd

abc

abcabcabcabc

abc

aabacbaabbaaz

aab

aaaaaa

aa

Sample Output

Case 1: 0

Case 2: 4

Case 3: 2

Case 4: 5

Hint

Dataset is huge, use faster I/O methods.

算法:KMP

 1 #include <iostream>
 2 #include <string>
 3 #include <cstdio>
 4 #include <cstring>
 5 using namespace std;
 6 
 7 const int maxn = 1000001;
 8 char pattern[maxn], target[maxn];
 9 int prefix[maxn];
10 int lenp, lent;
11 int cnt, t, ca;
12 
13 void GetPrefix()
14 {
15     int i = 0, j = -1;
16     prefix[0] = -1;
17     while(i < lenp)
18     {
19         if(j == -1 || pattern[i] == pattern[j])
20         {
21             i++;
22             j++;
23             prefix[i] = j;
24         }
25         else j = prefix[j];
26     }
27 }
28 
29 void KMP()
30 {
31     GetPrefix();
32     int i = 0, j = 0;
33     while(i < lent)
34     {
35         if(target[i] == pattern[j] || j == -1)
36         {
37             j++;
38             i++;
39         }
40         else j = prefix[j];
41         if(j == lenp)
42         {
43             j = prefix[j];
44             cnt++;
45         }
46     }
47 }
48 
49 int main()
50 {
51     scanf("%d", &t);
52     ca = 1;
53     while(t--)
54     {
55         scanf("%s %s", target, pattern);
56         lenp = strlen(pattern);
57         lent = strlen(target);
58         cnt = 0;
59         KMP();
60         printf("Case %d: %d\n", ca++, cnt);
61     }
62     return 0;
63 }

 

posted on 2013-04-08 13:17  铁树银花  阅读(377)  评论(0编辑  收藏  举报

导航