BNU 13174 substring frequency

Source: Internet
Author: User
3c. substring frequencytime limit: 1000 msmemory limit: 32768kb64-bit integer Io format: % LLD Java class name: Main

A string is a finite sequence of symbols that are chosen from an alphabet. In this problem you are given two non-empty stringsAAndB, Both contain lower case English characters. You have to find the number of timesBOccurs as a substringA.

Input

Input starts with an integerT (≤ 5), Denoting the number of test cases.

Each case starts with two lines. First line containsAAnd second line containsB. You can assume1 ≤length (A), length (B) ≤106.

Output

For each case, print the case number and the number of timesBOccurs as a substringA.

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

 

Solution: use bare KMP ..........

 

 1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #include <algorithm> 6 #include <climits> 7 #include <vector> 8 #include <queue> 9 #include <cstdlib>10 #include <string>11 #include <set>12 #define LL long long13 #define INF 0x3f3f3f3f14 using namespace std;15 int fail[1000010];16 char str[1000020],p[1000010];17 void getFail(int &len){18     fail[0] = fail[1] = 0;19     len = strlen(p);20     for(int i = 1; i < len; i++){21         int j = fail[i];22         while(j && p[i] != p[j]) j = fail[j];23         fail[i+1] = p[i] == p[j]?j+1:0;24     }25 }26 int main(){27     int t,i,j,len,ans,k = 1;28     scanf("%d",&t);29     while(t--){30         scanf("%s%s",str,p);31         getFail(len);32         j = ans = 0;33         for(i = 0; str[i]; i++){34             while(j && str[i] != p[j]) j = fail[j];35             if(str[i] == p[j]) j++;36             if(j == len) ans++;37         }38         printf("Case %d: %d\n",k++,ans);39     }40     return 0;41 }
View code

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.