SA(后缀数组)
题目大意:给你一个字符串,将这个字符串的所有非空后缀按字典序排序。 输出排序后每个字符串对应的后缀位置。
solution:
一、朴素算法
将所有字符串进行快速排序。
快排复杂度为 ,其中cmp函数的复杂度为 。 总复杂度为 。
二、倍增 + 快排
首先,以每个后缀的第一个字符为第一关键字,进行排序。然后以第二、第三个字符为关键字进行排序…。
总共进行 次排序,每次复杂度为 。总复杂度为 。
三、倍增 + 基数排序
倍增思想不变,但将 的快排换为了 的基数排序。
进行 次排序,每次复杂度为 。总复杂度为 。
code:
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define ls(p) (p) << 1
#define rs(p) (p) << 1 | 1
inline int rd() {
int x=0,f=1; char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-48;ch=getchar();}
return x*f;
}
const int N = 2e6 + 5;
const int P = 1e9 + 7;//998244353
const int INF = 1e18;
int n, m, sa[N], x[N], y[N], c[N];
string s;
void SA () {
for (int i = 1; i <= n; i++) c[x[i] = s[i]]++;
for (int i = 2; i <= m; i++) c[i] += c[i - 1];
for (int i = n; i >= 1; i--) sa[c[x[i]]--] = i;
for (int k = 1; k <= n; k <<= 1) {
int cnt = 0; memset (c, 0, sizeof c);
for (int i = n - k + 1; i <= n; i++) y[++cnt] = i;
for (int i = 1; i <= n; i++) if (sa[i] > k) y[++cnt] = sa[i] - k;
for (int i = 1; i <= n; i++) c[x[i]]++;
for (int i = 2; i <= m; i++) c[i] += c[i - 1];
for (int i = n; i >= 1; i--) sa[c[x[y[i]]]--] = y[i], y[i] = 0;
swap (x, y); x[sa[1]] = 1; cnt = 1;
for (int i = 2; i <= n; i++)
if (y[sa[i]] == y[sa[i - 1]] && y[sa[i] + k] == y[sa[i - 1] + k])
x[sa[i]] = cnt;
else x[sa[i]] = ++cnt;
if (cnt == n) break;
m = cnt;
}
}
void solve () {
cin >> s;
n = s.size(); m = 'z';
s = "?" + s;
SA();
for (int i = 1; i <= n; i++) cout << sa[i] << " ";
}
signed main () {
// freopen (".in", "r", stdin);
// freopen (".out", "w", stdout);
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int tid = 0, T = 1; // cin >> tid >> T;
while (tid + 1 && T--) solve ();
return 0;
}