JZOJ3291. 【JSOI2013】快乐的JYY

Description

给定两个字符串A和B,表示JYY的两个朋友的名字。我们用A(i,j)表示A字符串中从第i个字母到第j个字母所组成的子串。同样的,我们也可以定义B(x,y)。
JYY发现两个朋友关系的紧密程度,等于同时满足如下条件的四元组(i,j,x,y)的个数:
1) 1≤i≤j≤|A|
2) 1≤x≤y≤|B|
3)A(i,j)=B(x,y)
4) A(i,j)为回文串
这里|A|表示字符串A的长度。
JYY希望你帮助他计算出这两个朋友之间关系的紧密程度。

Input

数据包行两行由大写字母组成的字符串A和B。

Output

输出文件包含一行一个整数,表示紧密程度,也就是满足要求的4元组个数。

Sample Input

输入1:
PUPPY
PUPPUP
输入2:
PUPPY
KFC

Sample Output

输出1:
17
输出2:
0

Data Constraint

对于10%的数据满足|A|,|B|≤50;
对于30%的数据满足|A|,|B| ≤ 1000;
对于40%的数据满足|A|≤1000;
对于60%的数据满足|A|≤4000;
对于额外20%的数据满足A=B;
对于100%的数据满足1 ≤|A|,|B| ≤ 50000。

题解

很显然,是个回文自动机。
于是就这样了。
对A和B分别建一个自动机,
然后就在上面跑一次就好了。

code

#include <queue>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string.h>
#include <cmath>
#include <math.h>
#include <time.h>
#define ll long long
#define N 100003
#define M 103
#define db double
#define P putchar
#define G getchar
#define inf 998244353
#define pi 3.1415926535897932384626433832795
using namespace std;
char ch;
void read(int &n)
{
    n=0;
    ch=G();
    while((ch<'0' || ch>'9') && ch!='-')ch=G();
    ll w=1;
    if(ch=='-')w=-1,ch=G();
    while('0'<=ch && ch<='9')n=(n<<3)+(n<<1)+ch-'0',ch=G();
    n*=w;
}

int max(int a,int b){return a>b?a:b;}
int min(int a,int b){return a<b?a:b;}
ll abs(ll x){return x<0?-x:x;}
ll sqr(ll x){return x*x;}
void write(ll x){if(x>9) write(x/10);P(x%10+'0');}

struct node
{
    int son[27],v,len,fail;
}S[2][N];

char t[N];
int lena,lenb,s,m,lst;
ll ans;

int newone(int op,int l)
{
    S[op][++s].len=l;
    return s;
}

void pre(int op)
{
    s=m=lst=0;
    newone(op,-1);
    newone(op,0);
    t[m]=-1;
    S[op][0].fail=1;
}

int fail(int op,int x)
{
    for(;t[m-S[op][x].len-1]!=t[m];x=S[op][x].fail);
    return x;
}

void ins(int op,int w)
{
    t[++m]=w;
    int p=fail(op,lst);
    if(!S[op][p].son[w])
    {
        int id=newone(op,S[op][p].len+2);
        S[op][id].fail=S[op][fail(op,S[op][p].fail)].son[w];
        S[op][p].son[w]=id;
    }
    lst=S[op][p].son[w];
    S[op][lst].v++;
}

void calc(int op)
{
    for(int i=s;i;i--)
        S[op][S[op][i].fail].v+=S[op][i].v;
}

void dfs(int x,int y)
{
    if(S[0][x].len>0)
        ans+=(ll)S[0][x].v*S[1][y].v;
    for(int i=0;i<26;i++)
        if(S[0][x].son[i] && S[1][y].son[i])
            dfs(S[0][x].son[i],S[1][y].son[i]);
}

int main()
{   
    for(ch=G();ch<'A' || ch>'Z';ch=G());pre(0);
    for(;'A'<=ch && ch<='Z';ch=G())ins(0,ch-'A');
    calc(0);

    for(ch=G();ch<'A' || ch>'Z';ch=G());pre(1);
    for(;'A'<=ch && ch<='Z';ch=G())ins(1,ch-'A');
    calc(1);

    dfs(0,0);dfs(1,1);
    printf("%lld",ans);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/lijf2001/article/details/81006673