BZOJ3998: [TJOI2015]弦論(後綴自動機)

Time Limit: 10 Sec  Memory Limit: 256 MB
Submit: 4018  Solved: 1477
[Submit][Status][Discuss]

Description

對於一個給定長度爲N的字符串,求它的第K小子串是什麼。php

Input

 第一行是一個僅由小寫英文字母構成的字符串Sspa

第二行爲兩個整數T和K,T爲0則表示不一樣位置的相同子串算做一個。T=1則表示不一樣位置的相同子串算做多個。K的意義如題所述。

Output

輸出僅一行,爲一個數字串,爲第K小的子串。若是子串數目不足K個,則輸出-1code

Sample Input

aabc
0 3

Sample Output

aab

HINT

 

 N<=5*10^5blog


T<2

K<=10^9

Source

 

這題和上一題同樣啊,若是統計相同的就把$right$集合大小算上就好了。。ip

仍是不會寫代碼字符串

 

 

#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; 
}
相關文章
相關標籤/搜索