Reprint please indicate the source, thank you http://blog.csdn.net/ACM_cxlove? Viewmode = Contents
By --- cxlove
Question: Give a string to query which substring is in the K Lexicographic Order
Http://www.spoj.pl/problems/SUBLEX/
As Sam can traverse all the substrings, it only needs to pre-process the number of substrings in the future of a node.
First, each node is used as the final state to calculate a substring, so the initialization count is 1.
Then, follow the topological order to update the pre. Similar to the number DP.
When spoj is very slow, various optimizations are required. The first is the classic topology.
One pre-processing, save all the subsequent operations as corresponding letters.
Note that when querying, there is a K --. Because ending with the current letter is also a substring, you need to remove
#include<iostream>#include<cstdio>#include<map>#include<cstring>#include<cmath>#include<vector>#include<algorithm>#include<set>#include<string>#include<queue>#define inf 100000005#define M 40#define N 200015#define maxn 300005#define eps 1e-10#define zero(a) fabs(a)<eps#define Min(a,b) ((a)<(b)?(a):(b))#define Max(a,b) ((a)>(b)?(a):(b))#define pb(a) push_back(a)#define mp(a,b) make_pair(a,b)#define mem(a,b) memset(a,b,sizeof(a))#define LL unsigned long long#define MOD 1000000007#define lson step<<1#define rson step<<1|1#define sqr(a) ((double)(a)*(a))#define Key_value ch[ch[root][1]][0]#define test puts("OK");#pragma comment(linker, "/STACK:1024000000,1024000000")using namespace std;struct SAM{ SAM *pre,*son[26]; int len,cnt;}*root,*tail,que[N],*b[N];char str[N/2];int son[N][26],cnt[N];int tot=0;int c[N];char ch[N][26];void add(int c,int l){ SAM *p=tail,*np=&que[tot++]; np->len=l; while(p&&p->son[c]==NULL) p->son[c]=np,p=p->pre; if(p==NULL) np->pre=root; else { SAM *q=p->son[c]; if(p->len+1==q->len) np->pre=q; else { SAM *nq=&que[tot++]; *nq=*q; nq->len=p->len+1; np->pre=q->pre=nq; while(p&&p->son[c]==q) p->son[c]=nq,p=p->pre; } } tail=np;}void slove(int k){ int l=0; int now=0; while(k) { for(int i=0;i<cnt[now];i++) { if(k>que[son[now][i]].cnt) { k-=que[son[now][i]].cnt; } else { str[l++]=ch[now][i]; now=son[now][i]; k--; break; } } } str[l]='\0'; puts(str);}int main(){ root=tail=&que[tot++]; scanf("%s",str); int l=strlen(str); for(int i=0;str[i];i++) add(str[i]-'a',i+1); for(int i=0;i<tot;i++) c[que[i].len]++; for(int i=1;i<tot;i++) c[i]+=c[i-1]; for(int i=0;i<tot;i++) b[--c[que[i].len]]=&que[i]; for(int i=0;i<tot;i++) que[i].cnt=1; for(int i=tot-1;i>=0;i--) { SAM *p=b[i]; for(int j=0;j<26;j++) { if(p->son[j]) { int u=p-que,v=p->son[j]-que; son[u][cnt[u]]=v; ch[u][cnt[u]++]=j+'a'; p->cnt+=p->son[j]->cnt; } } } int q,k; scanf("%d",&q); while(q--) { scanf("%d",&k); slove(k); } return 0;}