zoj3587(kmp+dp)

Marlon's String

Time Limit: 2 Seconds       Memory Limit: 65536 KB

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


最开始看到这题就觉得是个dp,但是不知道从何做起,,还以为要用exkmp,(还不怎么会),后来发现也是用next数组性质就可以解决的题,,想复杂了。。。。假设前一个串是S串,后一个是T串,可以通过kmp求出T串第I个位置位置之前子串为前缀时在S串中出现过几次,同理反转以后也可以求出i+1位置之后的子串为后缀时出现在S串中的次数,相乘既是当前组合出现方案数,然后全加起来就行,而当前位置失败不匹配时有vis[next[i]]+=vis[i];所以dp搞一搞就好了。注意字符串很长,所以要用long long(在这里WA了一次T.T)

#include 
#include 
#include 
#define mem(a) memset((a),0,sizeof(a))
#define LL long long
using namespace std;
char s[100000+10];
char t[100000+10];
int ntr[100000+10];
LL vis1[100000+10];
LL vis2[100000+10];
void get_ntr(char *s)
{
    int i=0,j=-1;
    ntr[i]=-1;
    int len=strlen(s);
    while(i<=len)
    {
        if(j==-1||s[i]==s[j])
        {
            i++;
            j++;
            ntr[i]=j;
        }
        else
            j=ntr[j];
    }
}
void kmp1(char *s,char *t)
{
    int i=0,j=0;
    int lens=strlen(s);
    while(i0; i--)
            if(ntr[i]!=-1) vis1[ntr[i]]+=vis1[i];
        for(int i=0; i0; i--)
            if(ntr[i]!=-1)vis2[ntr[i]]+=vis2[i];
        LL ans=0;
        for(int i=1; i


你可能感兴趣的:(kmp)