• 【洛谷 P4248】 [AHOI2013]差异(后缀自动机)


    题目链接

    [ans=sum_{1<=i<j<=n}len(T_i)+len(T_j)-2*lcp(T_i,T_j) ]

    观察这个式子可以发现,前面两个(len)是常数,后面的其实就是反串有每对前缀的相同后缀乘以其长度之和。
    两个前缀的相同后缀就是这两个串在parent tree上对应的点的(LCA),于是直接树上统计就行了。

    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    const int MAXN = 1000010;
    struct SAM{
        int ch[26];
        int len, fa;
    }sam[MAXN << 1];
    int las = 1, cnt = 1, f[MAXN << 1];
    struct Edge{
        int next, to;
    }e[MAXN << 1];
    int head[MAXN << 1], num, n;
    inline void Add(int from, int to){
        e[++num].to = to; e[num].next = head[from]; head[from] = num;
    }
    inline void add(int c){
        int p = las; int np = las = ++cnt;
        sam[np].len = sam[p].len + 1; f[cnt] = 1;
        for(; p && !sam[p].ch[c]; p = sam[p].fa) sam[p].ch[c] = np;
        if(!p) sam[np].fa = 1;
        else{
            int q = sam[p].ch[c];
            if(sam[q].len == sam[p].len + 1) sam[np].fa = q;
            else{
                int nq = ++cnt; sam[nq] = sam[q];
                sam[nq].len = sam[p].len + 1;
                sam[q].fa = sam[np].fa = nq;
                for(; p && sam[p].ch[c] == q; p = sam[p].fa) sam[p].ch[c] = nq;
            }
        }
    }
    char a[MAXN];
    long long ans;
    void dfs(int u){
        long long tmp = 0;
        for(int i = head[u]; i; i = e[i].next){
            dfs(e[i].to);
            tmp += (long long)f[u] * f[e[i].to];
            f[u] += f[e[i].to];
        }
        ans += (long long)tmp * 2 * sam[u].len;
    }
    int main(){
        scanf("%s", a + 1);
        n = strlen(a + 1);
        for(int i = 1; i <= n; ++i)
           add(a[i] - 'a');
        for(int i = 2; i <= cnt; ++i)
            Add(sam[i].fa, i);
        dfs(1);
        printf("%lld
    ", (long long)n * (n - 1) * (n + 1) / 2 - ans);
        return 0;
    }
    
    
  • 相关阅读:
    Mybatis入门
    Spring的xml文件配置方式实现AOP
    jquery简直是太酷炫强大了
    [Google Guava] 2.2-新集合类型
    小规模的流处理框架.Part 1: thread pools
    数据库三大范式和五大约束
    Hibernate:缓存
    MyBatis:缓存配置
    Python:协程
    微信公众号开发之测试账号
  • 原文地址:https://www.cnblogs.com/Qihoo360/p/10986434.html
Copyright © 2020-2023  润新知