Description
给以长度为 \(n\) 的字符串,要求每次只能从两边取一个字符,使得取出来之后字典序最小。
\(1\leq n\leq 30000\)
Solution
将字符串翻转后加在原字符串后,求个后缀排名。直接比较排名来判断取前还是取后。
Code
#include <bits/stdc++.h>
using namespace std;
const int N = (30000+5)<<1;
char ch[N];
int n, m, x[N<<1], y[N<<1], c[N], sa[N], rk[N];
void get() {
for (int i = 1; i <= n; i++) c[x[i] = ch[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 num = 0;
for (int i = n-k+1; i <= n; i++) y[++num] = i;
for (int i = 1; i <= n; i++) if (sa[i] > k) y[++num] = sa[i]-k;
for (int i = 1; i <= m; i++) c[i] = 0;
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];
swap(x, y); x[sa[1]] = num = 1;
for (int i = 2; i <= n; i++)
x[sa[i]] = (y[sa[i]] == y[sa[i-1]] && y[sa[i]+k] == y[sa[i-1]+k]) ? num : ++num;
if ((m = num) == n) break;
}
for (int i = 1; i <= n; i++) rk[sa[i]] = i;
}
void work() {
scanf("%d", &n); getchar();
for (int i = 1; i <= n; i++) {
scanf("%c", &ch[i]); getchar();
ch[(n<<1)+2-i] = ch[i];
}
ch[n+1] = '$'; n = (n<<1)+1; m = 100;
get();
for (int i = 1, lm = (n>>1), l = 1, r = lm; i <= lm; i++) {
if (rk[l] <= rk[n-r+1]) putchar(ch[l++]);
else putchar(ch[r--]);
if (i%80 == 0) puts("");
}
}
int main() {work(); return 0; }