BZOJ 4566: [Haoi2016]找相同字符 後綴自動機

Description
給定兩個字符串,求出在兩個字符串中各取出一個子串使得這兩個子串相同的方案數。兩個方案不同當且僅當這兩
個子串中有一個位置不同。

Input

兩行,兩個字符串s1,s2,長度分別爲n1,n2。1 <=n1, n2<= 200000,字符串中只有小寫字母

Output

輸出一個整數表示答案

Sample Input
aabb
bbaa
Sample Output
10

題解:
據說sa也能做?但是我還是隻會後綴自動機的做法。對兩個串放在一起做一個廣義後綴自動機,建完之後由下至上統計出每個字符串在兩個串中出現的次數,答案就是所有的(o->max_len-o->parent->max_len)*(sum[0]*sum[1])

#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<iomanip>
#include<cstring>
#include<string>
#include<algorithm>
#include<ctime>
#include<cmath>
using namespace std;
struct sam
{
    sam *parent;
    sam *son[26];
    int max_len;
    int siz[2];
    int id;
    sam(){}
    void* operator new (size_t,int _,int id);
}mempool[800000];
int T;
void* sam :: operator new (size_t,int _,int id)
{
    T++;
    sam *o=&mempool[T];
    o->id=T;
    o->max_len=_;
    if(id!=-1) o->siz[id]++;
    return o;
}
sam* root=new(0,-1) sam,*last=root;
char s[400000];
void Insert(int zm,int id)
{
    sam *p=last;
    sam *np=new (p->max_len+1,id) sam;
    while(p && !p->son[zm])
    {
        p->son[zm]=np;
        p=p->parent;
    }
    if(!p) np->parent=root;
    else
    {
        sam *q=p->son[zm];
        if(q->max_len==p->max_len+1) np->parent=q;
        else
        {
            sam *nq=new (p->max_len+1,-1) sam;
            nq->parent=q->parent;
            memcpy(nq->son,q->son,sizeof(nq->son));
            q->parent=nq;
            np->parent=nq;
            while(p && p->son[zm]==q)
            {
                p->son[zm]=nq;
                p=p->parent;
            }
        }       
    }
    last=np;            
}
struct bian
{
    int l,r;
}a[1000000];
int fir[1000000];
int nex[1000000];
int tot=1;
void add_edge(int l,int r)
{
    a[++tot].l=l;
    a[tot].r=r;
    nex[tot]=fir[l];
    fir[l]=tot;
}
void get_bian()
{   
    for(int i=2;i<=T;i++)
        add_edge(mempool[i].parent->id,mempool[i].id);
}
long long ans=0;
void dfs(int u)
{
    for(int o=fir[u];o;o=nex[o])
    {
        dfs(a[o].r);
        mempool[u].siz[0]+=mempool[a[o].r].siz[0];
        mempool[u].siz[1]+=mempool[a[o].r].siz[1];
    }
    if(u!=1)
    {
        int ben=mempool[u].max_len-mempool[u].parent->max_len;
        ans+=1ll*ben*mempool[u].siz[0]*mempool[u].siz[1];
    }
}
int main()
{
    scanf("%s",s+1);
    int len=strlen(s+1);
    for(int i=1;i<=len;i++) Insert(s[i]-'a',0);
    last=root;
    scanf("%s",s+1);
    len=strlen(s+1);
    for(int i=1;i<=len;i++) Insert(s[i]-'a',1);
    get_bian();
    dfs(1);
    printf("%lld\n",ans);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章