BZOJ3998: [TJOI2015]弦论(后缀自动机)

时间:2022-06-04
本文章向大家介绍BZOJ3998: [TJOI2015]弦论(后缀自动机),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Time Limit: 10 Sec  Memory Limit: 256 MB

Submit: 4018  Solved: 1477

[Submit][Status][Discuss]

Description

对于一个给定长度为N的字符串,求它的第K小子串是什么。

Input

 第一行是一个仅由小写英文字母构成的字符串S

第二行为两个整数T和K,T为0则表示不同位置的相同子串算作一个。T=1则表示不同位置的相同子串算作多个。K的意义如题所述。

Output

输出仅一行,为一个数字串,为第K小的子串。如果子串数目不足K个,则输出-1

Sample Input

aabc 0 3

Sample Output

aab

HINT

 N<=5*10^5

T<2

K<=10^9

Source

这题和上一题一样啊,如果统计相同的就把$right$集合大小算上就行了。。

还是不会写代码

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int MAXN = 1e6 + 10;
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
char s[MAXN];
int opt, K, N;
int fa[MAXN], len[MAXN], ch[MAXN][27], siz[MAXN], right[MAXN], tot = 1, last = 1, root = 1;
void insert(int x) {
    int now = ++tot, pre = last; last = now; len[now] = len[pre] + 1; 
    right[now] = 1;
    for(; pre && !ch[pre][x]; pre = fa[pre]) ch[pre][x] = now;
    if(!pre) fa[now] = root;
    else {
        int q = ch[pre][x];
        if(len[q] == len[pre] + 1) fa[now] = q;
        else {
            int nows = ++tot; len[nows] = len[pre] + 1;
            memcpy(ch[nows], ch[q], sizeof(ch[q]));
            fa[nows] = fa[q]; fa[q] = fa[now] = nows;
            for(; pre && ch[pre][x] == q; pre = fa[pre]) ch[pre][x] = nows;
        }
    }
}    
void Query(int K) {
    int now = root;
    if(K > siz[root]) return (void) printf("-1");
    while(K) {
        if(now != root) K -= right[now];
        if(K <= 0) break;
        for(int i = 0; i <= 25; i++) 
            if(ch[now][i]) {
                if(siz[ch[now][i]] >= K) {putchar(i + 'a'); now = ch[now][i]; break; }
                else K -= siz[ch[now][i]];        
            }
    }
    puts("");
}
void Topsort() {
    static int A[MAXN], a[MAXN]; 
    for(int i = 1; i <= tot; i++) A[len[i]]++;
    for(int i = 1; i <= N; i++)   A[i] += A[i - 1];
    for(int i = tot; i >= 1; i--) a[A[len[i]]--] = i;
    //for(int i = 1; i <= tot; i++) siz[i] = 1;
    
    if(opt == 1) 
        for(int i = tot; i; i--) right[fa[a[i]]] += right[a[i]];
    if(opt == 0) 
        for(int i = tot; i; i--) right[a[i]] = 1;
    for(int i = tot; i; i--) {
        siz[a[i]] = right[a[i]];
        for(int j = 0; j <= 25; j++)
            siz[a[i]] += siz[ch[a[i]][j]];    
    }    
}
int main() {
#ifdef WIN32
    freopen("a.in", "r", stdin);
#endif
    scanf("%s", s + 1);
    opt = read(), K = read();
    N = strlen(s + 1);
    for(int i = 1; i <= N; i++) insert(s[i] - 'a');
    Topsort(); 
    Query(K); 
    return 0; 
}