Suffix Array
You're half a world away
But in my mind I whisper every single word you say
The Suffix Array (SA) is used to address the following problem:
You are given a string
s of lengthn (0-indexed); sort all of then suffixes ofs , in lexicographically increasing order.Output the answer as a permutation
p , wherep_x=i indicates that the suffixs[i\cdots (n-1)] is the(x+1) -th smallest among all suffixes.
Brute Force
Extract all suffixes from
Optimization 1
We do not need the full information from the entire strings of all
For convenience, we are going to sort all cyclic shifts instead of the suffixes of .). It can be shown that the solution for our new problem is identical to the original one.
In the
For example, when
To sort by the order of the characters in
Since we have
Optimization 1.1
The range of
Optimization ?
There is a solution in linear time.
Implementation
A minor constant optimization: Notice that we don't need to actually do the first sort in every iteration; just apply
int n;
inline int f(int x,int i){
x+=(1<<(i-1));
if(x>=n) x-=n;
return x;
}
void solve(){
string s;
cin>>s,n = s.length(),s+='$',n++;
vector<int> p(n),c(n);
map<char,int> mp;
for(char c:s) mp[c]++;
for(auto it=++mp.begin();it!=mp.end();it++) it->snd+=prev(it)->snd;
for(int i=n-1;i>=0;i--) p[--mp[s[i]]] = i;
int id = 0;
for(int l=0,r=0;l<n;l=r,id++){
while(r<n && s[p[l]]==s[p[r]]) c[p[r++]] = id;
}
id++;
for(int i=1;(1<<(i-1))<=n;i++){
for(int &j:p){
j-=1<<(i-1);
if(j<0) j+=n;
}
vector<int> tp = p,cnt(id);
for(int j:c) cnt[j]++;
for(int j=1;j<id;j++) cnt[j]+=cnt[j-1];
for(int j=n-1;j>=0;j--) p[--cnt[c[tp[j]]]] = tp[j];
id = 0;
auto tc = c;
tc[p[0]] = 0;
for(int j=1;j<n;j++){
if(tc[p[j-1]]==tc[p[j]] && tc[f(p[j-1],i)]==tc[f(p[j],i)]) c[p[j]] = id;
else c[p[j]] = ++id;
}
id++;
}
p.erase(p.begin());
for(int i:p) cout<<i+1<<" ";
cout<<"\n";
}
Author:
Misaka16172GenAI usage: only for grammar check.