SPOJ - SUBLEX Lexicographical Substring Search 求字典序第k小的子串

题目:求字符串字典序第k小的子串

思路:统计每个状态的子串的个数,按字典序寻找

代码:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define LL long long
#define ULL unsigned long long
#define INF 0x3f3f3f3f
#define mm(a,b) memset(a,b,sizeof(a))
#define PP puts("*********************");
template T f_abs(T a){ return a > 0 ? a : -a; }
template T gcd(T a, T b){ return b ? gcd(b, a%b) : a; }
template T lcm(T a,T b){return a/gcd(a,b)*b;}
// 0x3f3f3f3f3f3f3f3f
//0x3f3f3f3f

const int MAXN = 200050, SIZE = 26;
struct SAM {
    int len[MAXN], link[MAXN], next[MAXN][SIZE];
    int total, last;
    inline int newNode(int L) {
        len[++total] = L; link[total] = 0;
        for(int i = 0; i < SIZE; ++i) next[total][i] = 0;
        return total;
    }
    inline void Add(int c) {
        int i, p = last, cur = newNode(len[last] + 1);
        for(; p && !next[p][c]; p = link[p]) next[p][c] = cur;
        if(!p) link[cur] = 1;//令其指向初始状态
        else {
            int q = next[p][c];
            if(len[q] == len[p] + 1) link[cur] = q;
            else {//>
                int clone = newNode(len[p] + 1);
                for(i = 0; i < SIZE; ++i) next[clone][i] = next[q][i];
                link[clone] = link[q];
                link[q] = link[cur] = clone;
				for(; p && next[p][c] == q; p = link[p]) next[p][c] = clone;
            }
        }
        last = cur;
    }
    void Init () {//根节点是1
        total = 0;
        last = newNode(0);
    }
}sam;
char str[MAXN];
int num[MAXN],idx[MAXN];
int dp[MAXN];
void solve(int k){
    int now=1,L=0;
    while(k){
        for(int j=0;jdp[x])
                k-=dp[x];
            else{
                str[L++]='a'+j;
                now=x;
                k--;
                break;
            }
        }
    }
    str[L]='\0';
    puts(str);
}
int main(){

    int Q,k;
    scanf("%s",str);
        sam.Init();
        for(int i=0;str[i]!='\0';i++)
            sam.Add(str[i]-'a');
        for(int i=1;i<=sam.total;i++)
            num[i]=0;
        for(int i=1;i<=sam.total;i++)
            num[sam.len[i]]++;
        for(int i=1;i<=sam.total;i++)
            num[i]+=num[i-1];
        for(int i=1;i<=sam.total;i++)
            idx[num[sam.len[i]]--]=i;

        for(int i=sam.total;i>=1;i--){
            int now=idx[i];
            dp[now]=1;
            for(int j=0;j


你可能感兴趣的:(后缀自动机)