【BZOJ2882】—工艺(后缀自动机)
把串倍长建即可
#include<bits/stdc++.h>
using namespace std;
const int RLEN=1<<20|1;
inline char gc(){
static char ibuf[RLEN],*ib,*ob;
(ob==ib)&&(ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
return (ob==ib)?EOF:*ib++;
}
#define gc getchar
inline int read(){
char ch=gc();
int res=0,f=1;
while(!isdigit(ch))f^=ch=='-',ch=gc();
while(isdigit(ch))res=(res+(res<<2)<<1)+(ch^48),ch=gc();
return f?res:-res;
}
#define ll long long
#define re register
#define pii pair<int,int>
#define pic pair<int,char>
#define fi first
#define se second
#define pb push_back
#define cs const
#define bg begin
#define poly vector<int>
template<class T>inline void chemx(T &a,T b){a<b?a=b:0;}
template<class T>inline void chemn(T &a,T b){a>b?a=b:0;}
cs int N=600005;
int n;
int a[N];
namespace Sam{
cs int M=N<<1;
map<int,int> nxt[M];
int len[M],last,tot,fa[M],pos[M];
inline void init(){
last=tot=1;
}
inline void insert(int c){
int cur=++tot,p=last;last=cur;
len[cur]=len[p]+1;
for(;p&&!nxt[p][c];p=fa[p])nxt[p][c]=cur;
if(!p)fa[cur]=1;
else{
int q=nxt[p][c];
if(len[p]+1==len[q])fa[cur]=q;
else{
int clo=++tot;
fa[clo]=fa[q],len[clo]=len[p]+1;
nxt[clo]=nxt[q];
for(;p&&nxt[p][c]==q;p=fa[p])nxt[p][c]=clo;
fa[cur]=fa[q]=clo;
}
}
}
void dfs(int u,int dep){
cout<<nxt[u].bg()->fi;
if(dep==n)cout<<'\n',exit(0);
cout<<" ";dfs(nxt[u].bg()->se,dep+1);
}
inline void calc(){
dfs(1,1);
}
}
int main(){
n=read();
Sam::init();
for(int i=1;i<=n;i++){
a[i]=a[i+n]=read();
}
for(int i=1;i<=2*n;i++){
Sam::insert(a[i]);
}
Sam::calc();
}