题意:用sam解决最小表示法
思路:用SS建立后缀自动机,从根节点向后走,每次都贪心地选择最小的字典序的走法,这样一定能保证走n步。所以我们只需要记录一下每个状态的位置就行了。
记录位置的方法,我们可以注意到,每个前缀在后缀自动机中对应的状态是唯一的,而且后缀自动机中任意一个子串都可以表示为某个前缀的后缀,所以我们只需要为每一个前缀标出位置,因为fail可以理解为后缀指针,所以把沿着fail指针向上走所有的位置均可以在这个前缀的位置出现。
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int maxn = 40005;
int righ[2*maxn],pos[maxn<<1];
const int ch_size = 26;
int ans,Len;
struct SAM{
int fa[maxn<<1], // 后缀链接
ch[maxn<<1][ch_size],
len[maxn<<1], //该节点最长串的长度
tot, // 节点总数
last; // 代表当前的整个串
void init(){
tot = last = 0;
fa[0] = -1;
len[0] = 0;
memset( ch[0],0,sizeof(ch[0]) );
}
void extend( int x ){
int p = last;
int cur = ++tot;
memset( ch[cur],0,sizeof( ch[cur] ) );
len[cur] = len[last]+1;
while( p != -1 && !ch[p][x] ){
ch[p][x] = cur;
p = fa[p];
}
if( p == -1 ){
fa[cur] = 0;
}else {
int q = ch[p][x];
if (len[q] == len[p] + 1) {
fa[cur] = q;
} else {
int clone = ++tot;
len[clone] = len[p] + 1;
for (int i = 0; i < ch_size; i++) {
ch[clone][i] = ch[q][i];
}
fa[clone] = fa[q];
fa[q] = fa[cur] = clone;
while (p != -1) {
if (ch[p][x] == q)ch[p][x] = clone;
else break;
p = fa[p];
}
}
}
last = cur;
}
}g;
char str[maxn];
int b[maxn<<1],c[maxn];
void radix( int len ){
memset( c,0,sizeof(c) );
for( int i = 1;i <= g.tot;i++ ) c[ g.len[i] ]++;
for( int i = 2;i <= len;i++ ) c[ i ] += c[i-1];
for( int i = 1;i <= g.tot;i++ ) b[ c[ g.len[i] ]-- ] = i;
}
int main(){
int T;
scanf("%d",&T);
while(T--) {
scanf("%s", str+1);
g.init();
Len = strlen(str+1);
for (int i = 1; i <= Len; i++) {
g.extend(str[i] - 'a');
}
int p = 0;
for( int i = 1;i <= Len;i++ ){
int c = str[i]-'a';
p = g.ch[p][c];
pos[p] = i;
}
for (int i = 1; i <= Len; i++) {
g.extend(str[i] - 'a');
}
for( int i = 1;i <= Len;i++ ){
int c = str[i]-'a';
p = g.ch[p][c];
pos[p] = i+Len;
}
radix(Len<<1);
for( int i = g.tot;i >= 1;i-- ){
int j = b[i];
pos[ g.fa[j] ] = pos[ g.fa[j] ] ? min( pos[ g.fa[j] ],pos[j] ):pos[j];
}
p = 0;
for( int i = 1;i <= Len;i++ ){
for( int c = 0;c < 26;c++ ){
if( g.ch[p][c] ){
p = g.ch[p][c];
break;
}
}
}
int ans = pos[p] - Len+1;
for( int i = 0;i <= g.tot;i++ ) pos[i] = 0;
printf("%d\n",ans);
}
return 0;
};