题意: 给一个字符串,求出按函数的方法得到的B,B的所有以pi为起点的后缀按字典序排序。得到pi的序列。
思路:找后缀数组C(找到第i个后面与它相同字符的距离),可以证明B数组与C数组对应的后缀字典序是相反的。求c数组的时候有些操作也在下面地址里。
上面两个的地址 : 大佬地址
找出每个后缀数组后,排序就可以了,直接sort排序,比较会超时。所以用Manber和Myers发明的算法,最后反着输出。
O(nlogn) 挑战程序设计竞赛(第一版)378页有讲
我的代码:
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#include<bits/stdc++.h>
#define int long long
using namespace std;
typedef pair<int,int> pii;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const double eps = 1e-4;
const int mod = 1e9+7;
const int N = 100010;
int n,c[N],sa[N],tmp[N],ran[N],k;
char s[N];
bool cmp(int i,int j){
if(ran[i] != ran[j]) return ran[i] < ran[j];
int ri = i+k<=n+1?ran[i+k]:-1;
int rj = j+k<=n+1?ran[j+k]:-1;
return ri < rj;
}
void get_sa(){
for(int i=0;i<=n+1;i++){
sa[i] = i;
ran[i] = i<n+1?c[i]:-1;
}
for(k = 1;k <= n+1;k <<= 1){
sort(sa,sa+n+2,cmp);
tmp[sa[0]] = 0;
for(int i=1;i<=n+1;i++)
tmp[sa[i]] = tmp[sa[i-1]] + (cmp(sa[i-1],sa[i])?1:0);
for(int i=0;i<=n+1;i++) ran[i] = tmp[i];
}
}
void get_c(){
int ta = -1,tb = -1;
for(int i=n-1;i>=0;i--){
if(s[i] == 'a'){
if(ta == -1) c[i] = n,ta = i;
else c[i] = ta-i,ta = i;
}else{
if(tb == -1) c[i] = n,tb = i;
else c[i] = tb-i,tb = i;
}
}
c[n] = n+1;
}
signed main(){
// IOS;
#ifdef ddgo
freopen("C:/Users/asus/Desktop/ddgoin.txt","r",stdin);
#endif
while(cin>>n>>s){
get_c();
get_sa();
for(int i=n;i>=1;i--) cout<<sa[i]+1<<" ";
puts("");
}
return 0;
}