BZOJ4566:[HAOI2016]找相同字符(广义SAM)

来源:互联网 发布:淘宝卖家改价要收费吗 编辑:程序博客网 时间:2024/05/29 19:49

题面

题意:给你两个字符串,在两个字符串中各取出一个子串,问使得这两个子串相同的方案数。两个方案不同当且仅当这两个子串中有一个位置不同。

字符串只会SAM的我终于找到了1道一眼题。

将两个串建出广义SAM,每个状态对于两个串分别求出一个Right集,
记为r1与r2。

每个状态的贡献就为r1r2(maxmin+1)

而对于广义SAM,我的XJB建法会出现很多空状态(就是max-min+1=0的状态)
以前想过是对计数大概没什么影响。
但是我发现了,本来求Right集大小可以将状态排序,由dep大的向dep小的更新。

但对于广义SAM,就要老老实实用dfs求了。
因为存在相同的dep使得更新的顺序乱了。(吓得我还以为SAM建错了)

#include <iostream>#include <fstream>#include <algorithm>#include <cmath>#include <ctime>#include <cstdio>#include <cstdlib>#include <cstring>using namespace std;#define mmst(a, b) memset(a, b, sizeof(a))#define mmcp(a, b) memcpy(a, b, sizeof(b))typedef long long LL;const int N=800800;int n;int son[N][26],dep[N],pre[N],r[N][2],cnt=1,last=1;int head[N],to[N],nex[N],cur;char cc[N];LL ans;void add(int u,int v){    to[++cur]=v;    nex[cur]=head[u];    head[u]=cur;}void dfs(int x){    for(int h=head[x];h;h=nex[h])    {        dfs(to[h]);        r[x][0]+=r[to[h]][0];        r[x][1]+=r[to[h]][1];    }}void insert(int x,int ops){    dep[++cnt]=dep[last]+1;    int np=cnt,p=last;    last=cnt;    r[cnt][ops]=1;    for(;!son[p][x];p=pre[p])    son[p][x]=np;    if(!p)    pre[np]=1;    else    {        int q=son[p][x];        if(dep[p]+1==dep[q])        pre[np]=q;        else        {            dep[++cnt]=dep[p]+1;            int nq=cnt;            pre[nq]=pre[q];            pre[q]=pre[np]=nq;            mmcp(son[nq],son[q]);            for(;son[p][x]==q;p=pre[p])            son[p][x]=nq;        }    }}int main(){    scanf("%s",cc);    n=strlen(cc);    for(int i=0;i<n;i++)    insert(cc[i]-'a',0);    last=1;    scanf("%s",cc);    n=strlen(cc);    for(int i=0;i<n;i++)    insert(cc[i]-'a',1);    for(int i=2;i<=cnt;i++)    add(pre[i],i);    dfs(1);    for(int i=2;i<=cnt;i++)    ans+=(LL)r[i][0]*r[i][1]*(LL)(dep[i]-dep[pre[i]]);    cout<<ans<<endl;    return 0;}

这里写图片描述