xtu字符串 C. Marlon's String

本文介绍了一个字符串匹配问题,即寻找所有可能的四元组(a,b,c,d),使得两个字符串S的子串Sa..b与Sc..d连接后等于第三个字符串T。通过使用KMP算法进行前后缀匹配,并给出了一段实现该算法的C++代码。

C. Marlon's String

Time Limit: 2000ms
Memory Limit: 65536KB
64-bit integer IO format: %lld      Java class name: Main
 
 

Long long ago, there was a coder named Marlon. One day he picked two string on the street. A problem suddenly crash his brain...

Let Si..j denote the i-th character to the j-th character of string S.

Given two strings S and T. Return the amount of tetrad (a,b,c,d) which satisfy Sa..b + Sc..d = T , ab and cd.

The operator + means concate the two strings into one.

Input

The first line of the data is an integer Tc. Following Tc test cases, each contains two line. The first line is S. The second line is T. The length of S and T are both in range [1,100000]. There are only letters in string S and T.

Output

For each test cases, output a line for the result.

Sample Input
1
aaabbb
ab
Sample Output
9

解题:与扩展KMP无关,与前缀有关。。。直接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 long
13 #define INF 0x3f3f3f3f
14 using namespace std;
15 int fail[100010];
16 char pa[100010],s[100010];
17 int a[100010],b[100010];
18 void kmp(int *arr){
19     int i,j,k;
20     fail[0] = fail[1] = 0;
21     for(i = 1; pa[i]; i++){
22         j = fail[i];
23         while(j && pa[i] != pa[j]) j = fail[j];
24         fail[i+1] = pa[j] == pa[i] ? j+1:0;
25     }
26     for(j = i = 0; s[i]; i++){
27         while(j && s[i] != pa[j]) j = fail[j];
28         if(pa[j] == s[i]){
29             arr[++j]++;
30         }
31     }
32     for(i = strlen(pa); i >= 0; i--)
33         if(fail[i]) arr[fail[i]] += arr[i];
34 }
35 int main(){
36     int t,i,len;
37     LL ans;
38     scanf("%d",&t);
39     while(t--){
40         scanf("%s %s",s,pa);
41         memset(a,0,sizeof(a));
42         memset(b,0,sizeof(b));
43         kmp(a);
44         reverse(s,s+strlen(s));
45         reverse(pa,pa+strlen(pa));
46         kmp(b);
47         ans = 0;
48         for(len = strlen(pa),i = 0; i < len; i++)
49             ans += (LL)a[i]*b[len-i];
50         printf("%lld\n",ans);
51     }
52     return 0;
53 }
View Code

 

转载于:https://www.cnblogs.com/crackpotisback/p/3877534.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值