码迷,mamicode.com
首页 > 其他好文 > 详细

SPOJ - SUBLEX 【后缀自动机】

时间:2018-01-16 23:55:08      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:put   int   math   putchar   第k小   while   i++   +=   using   

题目

求第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 【后缀自动机】

标签:put   int   math   putchar   第k小   while   i++   +=   using   

原文地址:https://www.cnblogs.com/Mychael/p/8298017.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!