字典序第 k 大
沿着自动机的边走即可,比较水的一道题吧.
Code:
#include <cstdio> #include <algorithm> #include <cstring> #define maxn 1000000 #define N 30 #define setIO(s) freopen(s".in","r",stdin) using namespace std; char str[maxn]; int opt,kth,n; struct SAM{ int tot,last; int ch[maxn][N],f[maxn],cnt[maxn],mx[maxn],C[maxn],rk[maxn],sumv[maxn]; void init(){tot=last=1;} void ins(int c) { int np = ++tot,p = last; last = np; mx[np] = mx[p] + 1; while(p && !ch[p][c]) ch[p][c] = np,p = f[p]; if(!p) f[np] = 1; else { int q = ch[p][c]; if(mx[q] == mx[p] + 1) f[np] = q; else { int nq = ++tot; f[nq] = f[q]; f[q] = f[np] = nq; mx[nq] = mx[p] + 1; memcpy(ch[nq], ch[q], sizeof(ch[q])); while(p && ch[p][c] == q) ch[p][c] = nq, p = f[p]; } } cnt[np] = 1; } void Solve() { for(int i = 1;i <= tot; ++i) ++C[mx[i]]; for(int i = 1;i <= tot; ++i) C[i] += C[i - 1]; for(int i = 1;i <= tot; ++i) rk[C[mx[i]]--] = i; for(int i = tot;i >= 1; --i) { int p = rk[i]; if(opt == 1) cnt[f[p]] += cnt[p], sumv[p] = cnt[p]; else sumv[p] = cnt[p] = 1; for(int i = 0;i < 29; ++i) sumv[p] += sumv[ch[p][i]]; } } char ans[maxn]; int id; void BFS(int k) { cnt[1] = sumv[1] = 0; int p = 1,con = 1,flag2 = 1; while(con && flag2) { int flag = 1; flag2 = 0; for(int i = 0;i < 29; ++i) { if(flag == 1) { flag = 0; if(k <= cnt[p]) {con = 0; break;} else k -= cnt[p]; } //printf("%d %d ",k,p); if(k > sumv[ch[p][i]]) k -= sumv[ch[p][i]]; else { ans[++id] = i + 'a',flag2 = 1, p = ch[p][i]; break; } } } if(!con) { for(int i = 1;i <= id; ++i) printf("%c",ans[i]); }else printf("-1"); } }T; int main(){ //setIO("input"); T.init(),scanf("%s",str),n = strlen(str); for(int i = 0;i < n; ++i) T.ins(str[i] - 'a'); scanf("%d",&opt),T.Solve(),scanf("%d",&kth),T.BFS(kth); return 0; }