一种离谱的后缀排序算法
如题,由于算法太离谱就投休闲娱乐了。
题目:P3809。
一眼看上去,这道题并不好做,因为直接排序不仅会超时,空间也容易超限。不过我们观察样例发现以 a 开头的后缀全都排在了 b 开头的后缀的前面,这一点显然是正确的。这启示我们把后缀按照首字母分类,先排 a 开头的,再排 b 开头的,以此类推。
现在考虑对所有 a 开头的后缀进行排序,我们发现这个过程可以递归进行,具体来说,我们可以继续把 a 开头的后缀按照下一个字母分类,分成 aa,ab,ac 等继续排序。我们很容易写出代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
inline int c2i(char c){
return c<='9'?(c-'0'):(c<='Z'?(c-'A'+10):(c-'a'+36));
}
int n;
string s;
vector<int> ans;
void suffix_sort(const array<vector<pair<int,int>>,62> &v){
for (const auto &i:v){
if (not i.empty()){
if (i.size()==1) ans.push_back(i[0].second);
else{
array<vector<pair<int,int>>,62> tmp;
for (auto [j,k]:i){
if (j==n) ans.push_back(k); // 后面没有字符了
else tmp[c2i(s[j+1])].push_back({j+1,k});
}
suffix_sort(tmp); // 递归排序
}
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin>>s;
n=s.length();
s='_'+s;
array<vector<pair<int,int>>,62> v;
for (int i=1;i<=n;i++) v[c2i(s[i])].push_back({i,i});
suffix_sort(v);
for (auto i:ans) cout<<i<<" ";
return 0;
}
分析一下复杂度,如果字符串为随机生成的,那么平均每次递归的大小都会除以字符集大小,所以仅需递归
但是我们发现最后一个点 MLE 了,我们思考为什么,如果字符串全部为同一种字符,那么每次递归只会减掉最后一个字符,这样时间和空间复杂度都被卡到了
我们可以判掉这种情况(当然不是对着数据判断),在排序的函数中加上一个深度限制,如果递归到达一定深度(这里我设的是
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
constexpr ull base=13331;
constexpr int lim=7;
inline int c2i(char c){
return c<='9'?(c-'0'):(c<='Z'?(c-'A'+10):(c-'a'+36));
}
int n;
string s;
vector<int> ans;
ull pw[1000001],h[1000001];
inline bool cmp(int u,int v){
int l=0,r=n-max(u,v),ans=-1;
while (l<=r){
int mid=(l+r)>>1;
if (h[u+mid]-h[u-1]*pw[mid+1]==h[v+mid]-h[v-1]*pw[mid+1]){
ans=mid;
l=mid+1;
}else{
r=mid-1;
}
}
if (ans>n-max(u,v)) return u>v;
else return s[u+ans+1]<s[v+ans+1];
}
void suffix_sort(const array<vector<pair<int,int>>,62> &v,int dep){
if (dep>=lim){
vector<int> tmp;
for (const auto &i:v){
if (not i.empty()){
for (auto [j,k]:i) tmp.push_back(k);
}
}
stable_sort(tmp.begin(),tmp.end(),cmp);
ans.insert(ans.end(),tmp.begin(),tmp.end());
return;
}
for (const auto &i:v){
if (not i.empty()){
if (i.size()==1) ans.push_back(i[0].second);
else{
array<vector<pair<int,int>>,62> tmp;
for (auto [j,k]:i){
if (j==n) ans.push_back(k);
else tmp[c2i(s[j+1])].push_back({j+1,k});
}
suffix_sort(tmp,dep+1);
}
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin>>s;
n=s.length();
s='_'+s;
pw[0]=1;
for (int i=1;i<=n;i++){
pw[i]=pw[i-1]*base;
h[i]=h[i-1]*base+s[i];
}
array<vector<pair<int,int>>,62> v;
for (int i=1;i<=n;i++) v[c2i(s[i])].push_back({i,i});
suffix_sort(v,0);
for (auto i:ans) cout<<i<<" ";
return 0;
}
改进后的算法时间复杂度最坏
AC 记录,可以看出,跑的并不慢。