题目大意
找一个环串的起点,使得从其开始遍历字典序最小
题解
建立后缀自动机,从根开始走length步,走到的点就是这个最小串的结尾,其step即表示它在串中的位置
step - n + 1即为开始位置
#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define LL long long int
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define BUG(s,n) for (int i = 1; i <= (n); i++) cout<<s[i]<<‘ ‘; puts("");
#define cls(x) memset(x,0,sizeof(x))
using namespace std;
const int maxn = 40005,maxm = 100005,INF = 1000000000;
inline int read(){
int out = 0,flag = 1; char c = getchar();
while (c < 48 || c > 57) {if (c == ‘-‘) flag = -1; c = getchar();}
while (c >= 48 && c <= 57) {out = (out << 3) + (out << 1) + c - ‘0‘; c = getchar();}
return out * flag;
}
int pre[maxn],step[maxn],ch[maxn][26],cnt,last,n;
char s[maxn];
void ins(int x){
int p = last,np = ++cnt; cls(ch[np]);
last = np; step[np] = step[p] + 1;
while (p && !ch[p][x]) ch[p][x] = np,p = pre[p];
if (!p) pre[np] = 1;
else {
int q = ch[p][x];
if (step[q] == step[p] + 1) pre[np] = q;
else {
int nq = ++cnt; step[nq] = step[p] + 1;
for (int i = 0; i < 26; i++) ch[nq][i] = ch[q][i];
pre[nq] = pre[q]; pre[np] = pre[q] = nq;
while (ch[p][x] == q) ch[p][x] = nq,p = pre[p];
}
}
}
void solve(){
int u = 1;
REP(i,n) for (int j = 0; j < 26; j++)
if (ch[u][j]){u = ch[u][j]; break;}
printf("%d\n",step[u] - n + 1);
}
int main(){
int T = read();
while (T--){
scanf("%s",s + 1);
n = strlen(s + 1); last = cnt = 1;
memset(ch[1],0,sizeof(ch[1]));
REP(i,n) ins(s[i] - ‘a‘);
REP(i,n) ins(s[i] - ‘a‘);
solve();
}
return 0;
}