SPOJ - SUBLEX 后缀自动机

Posted Mychael

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SPOJ - SUBLEX 后缀自动机相关的知识,希望对你有一定的参考价值。

题目

求第K小子串

题解

建好SAM后,拓扑排序,反向传递后面所形成的串的数量
最后从根开始,按照儿子形成串的数量与k比较走就好了

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define LL long long int
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
using namespace std;
const int maxn = 200005,maxm = 100005,INF = 1000000000;
inline int read(){
    int out = 0,flag = 1; char c = getchar();
    while (c < 48 || c > 57) {if (c == ‘-‘) flag = -1; c = getchar();}
    while (c >= 48 && c <= 57) {out = (out << 3) + (out << 1) + c - ‘0‘; c = getchar();}
    return out * flag;
}
int pre[maxn],sz[maxn],step[maxn],ch[maxn][26],cnt,last,n;
int a[maxn],b[maxn];
char s[maxn];
void ins(int x){
    int p = last,np = ++cnt;
    last = np; step[np] = step[p] + 1;
    while (p && !ch[p][x]) ch[p][x] = np,p = pre[p];
    if (!p) pre[np] = 1;
    else {
        int q = ch[p][x];
        if (step[q] == step[p] + 1) pre[np] = q;
        else {
            int nq = ++cnt; step[nq] = step[p] + 1;
            for (int i = 0; i < 26; i++) ch[nq][i] = ch[q][i];
            pre[nq] = pre[q]; pre[np] = pre[q] = nq;
            while (ch[p][x] == q) ch[p][x] = nq,p = pre[p];
        }
    }
}
void walk(int k){
    int u = 1;
    while (k){
        for (int i = 0; i < 26; i++) if (ch[u][i]){
            if (sz[ch[u][i]] >= k){
                putchar(i + ‘a‘);
                k--; u = ch[u][i];
                break;
            }else k -= sz[ch[u][i]];
        }
    }
    puts("");
}
void solve(){
    REP(i,cnt) b[step[i]]++;
    REP(i,cnt) b[i] += b[i - 1];
    REP(i,cnt) a[b[step[i]]--] = i;
    for (int i = cnt; i; i--){
        int u = a[i]; sz[u] = 1;
        for (int j = 0; j < 26; j++)
            if (ch[u][j]) sz[u] += sz[ch[u][j]];
    }
    int Q = read();
    while (Q--) walk(read());
}
int main(){
    scanf("%s",s + 1);
    n = strlen(s + 1); cnt = last = 1;
    REP(i,n) ins(s[i] - ‘a‘);
    solve();
    return 0;
}

以上是关于SPOJ - SUBLEX 后缀自动机的主要内容,如果未能解决你的问题,请参考以下文章

Lexicographical Substring Search SPOJ - SUBLEX (后缀自动机)

Lexicographical Substring Search SPOJ - SUBLEX (后缀数组)

SPOJ SUBLEX Lexicographical Substring Search - 后缀数组

SPOJ 7258 Lexicographical Substring Search(后缀自动机)

spoj7528 Lexicographical Substring Search

●SPOJ 7258 Lexicographical Substring Search