KMP,每匹配到一点就记录一下,然后用fail数组把已经匹配到的但是kmp没有记录的点加上。。。。
Time Limit: 2000MS | Memory Limit: 65536KB | 64bit IO Format: %lld & %llu |
[Submit] [Go Back] [Status]
Description
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 , a≤b and c≤d.
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
Source
[Submit] [Go Back] [Status]
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn=200000; int fail[maxn],n,m,c1[maxn],c2[maxn]; char S[maxn],T[maxn]; void getfail(char*T,int*f) { f[0]=f[1]=0; for(int i=1;i<m;i++) { int j=f[i]; while(j&&T[i]!=T[j]) j=fail[j]; f[i+1]=(T[i]==T[j])? j+1 : 0; } } void kmp(char*S,char*T,int*f,int* c) { getfail(T,f); int j=0; for(int i=0;i<n;i++) { while(j&&T[j]!=S[i]) j=f[j]; if(T[j]==S[i]) { j++; c[j]++; } } for(int i=m;i>=0;i--) if(f[i]) c[f[i]]+=c[i]; } int main() { int tk; scanf("%d",&tk); while(tk--) { scanf("%s%s",S,T); memset(c1,0,sizeof(c1)); memset(c2,0,sizeof(c2)); n=strlen(S);m=strlen(T); kmp(S,T,fail,c1); reverse(S,S+n); reverse(T,T+m); kmp(S,T,fail,c2); long long int ans=0; for(int i=0;i<m;i++) { ans+=(long long int)c1[i]*c2[m-i]; } printf("%lld\n",ans); } return 0; }