其他分享
首页 > 其他分享> > P4070 [SDOI2016]生成魔咒 - SAM

P4070 [SDOI2016]生成魔咒 - SAM

作者:互联网

这是一道板子题,考的是一个状态中不同子串数量为len[i] - len[fa[i]],即集合中最长的后缀减去最短的后缀。
不过这题我遇到的问题在于字符集过于庞大,最后是通过用map去代替ch数组解决。

//
// Created by acer on 2021/2/16.
//
//判断子串,不同子串个数,所有子串字典序第i大,最长公共子串

#include "bits/stdc++.h"
#define int long long
using namespace std;
const int MAXN = 1e5 + 10;

int len[MAXN << 1];
map<int,int> ch[MAXN<<1];
int fa[MAXN << 1];
int last = 1;
int tot = 1;
int p;

int add(int c) {
    p = last;
    last = ++tot;
    int np = last;
    len[np] = len[p] + 1;
    for (; p && !(ch[p][c]); p = fa[p]) ch[p][c] = np;
    if (!p) fa[np] = 1;
    else {
        int q = ch[p][c];
        if (len[q] == len[p] + 1) fa[np] = q;
        else {
            int nq = ++tot;
//            memcpy(ch[nq],ch[q],sizeof(ch[nq]));
            ch[nq] = ch[q];
            fa[nq] = fa[q];
            len[nq] = len[p] + 1;
            fa[np] = fa[q] = nq;
            for (; p && ch[p][c] == q; p = fa[p]) {
                ch[p][c] = nq;
            }
        }

    }
    return len[last] - len[fa[last]];

}

map<int,int> mp;
int main() {
    int n;cin >> n;
    int res = 0;
    int id = 0;
    for (int i = 1; i <= n; ++i) {
        int s;cin >> s;
        if (!mp[s]) mp[s] = ++id;
        res += add(mp[s]);
        cout << res << endl;
    }

}

标签:ch,SAM,int,len,fa,SDOI2016,np,nq,P4070
来源: https://blog.csdn.net/weixin_45509601/article/details/119219912