【LG4248】[AHOI2013]差异

【LG4248】[AHOI2013]差异

题面

洛谷

题解

后缀数组版做法戳我

我们将原串\(reverse\),根据后缀自动机的性质,两个后缀的\(lcp\)一定是我们在反串后两个前缀的\(lca\)

那么原式不就是求树上两两点对的距离和,

树上一条边的权值可以通过差分求出,就是\(i.len-i.fa.len\)

然后就统计每一条边的贡献就行了。

感觉少个log效率还跟sa差不多啊

代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring> 
#include <cmath> 
#include <algorithm>
using namespace std; 
const int MAX_N = 5e5 + 5; 
struct Node { int ch[26], len, fa; } t[MAX_N << 1]; 
int lst = 1, tot = 1, size[MAX_N << 1]; 
void extend(int c) { 
    int np = ++tot; 
    t[lst].ch[c] = np; 
    t[np].len = t[lst].len + 1; 
    int p = t[lst].fa; lst = np;
    while (p && !t[p].ch[c]) t[p].ch[c] = np, p = t[p].fa; 
    if (!p) t[np].fa = 1;
    else { 
        int q = t[p].ch[c];
        if (t[q].len == t[p].len + 1) t[np].fa = q; 
        else {
            int nq = ++tot; 
            t[nq] = t[q]; 
            t[nq].len = t[p].len + 1, t[q].fa = t[np].fa = nq; 
            while (p && t[p].ch[c] == q) t[p].ch[c] = nq, p = t[p].fa; 
        } 
    } 
    size[np] = 1; 
} 
int N, bln[MAX_N << 1], A[MAX_N << 1]; 
char a[MAX_N]; 
int main () { 
#ifndef ONLINE_JUDGE 
    freopen("cpp.in", "r", stdin); 
#endif 
    scanf("%s", a + 1); N = strlen(a + 1); 
    for (int i = 1; i <= N; i++) extend(a[N - i + 1] - 'a'); 
    for (int i = 1; i <= tot; i++) bln[t[i].len]++; 
    for (int i = 1; i <= tot; i++) bln[i] += bln[i - 1]; 
    for (int i = 1; i <= tot; i++) A[bln[t[i].len]--] = i;
    long long ans = 0; 
    for (int i = tot; i; i--) { 
        int x = A[i]; 
        size[t[x].fa] += size[x]; 
        ans += 1ll * (t[x].len - t[t[x].fa].len) * size[x] * (N - size[x]); 
    } 
    printf("%lld\n", ans); 
    return 0; 
} 

转载于:https://www.cnblogs.com/heyujun/p/10597399.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值