# [BZOJ 1692] [Usaco2007 Dec] 队列变换 【后缀数组 + 贪心】

---恢复内容开始---

### 代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>

using namespace std;

const int MaxL = 60000 + 15;

int n;
int A[MaxL], Rank[MaxL], SA[MaxL];
int VA[MaxL], VB[MaxL], VC[MaxL], Sum[MaxL];

char S[MaxL], Sout[MaxL];

inline bool Cmp(int *a, int x, int y, int l) {
return (a[x] == a[y]) && (a[x + l] == a[y + l]);
}

void DA(int *A, int n, int m) {
int *x, *y, *t;
x = VA; y = VB;
for (int i = 1; i <= m; ++i) Sum[i] = 0;
for (int i = 1; i <= n; ++i) ++Sum[x[i] = A[i]];
for (int i = 2; i <= m; ++i) Sum[i] += Sum[i - 1];
for (int i = n; i >= 1; --i) SA[Sum[x[i]]--] = i;
int p, q;
p = 0;
for (int j = 1; p < n; j <<= 1, m = p) {
q = 0;
for (int i = n - j + 1; i <= n; ++i) y[++q] = i;
for (int i = 1; i <= n; ++i) {
if (SA[i] <= j) continue;
y[++q] = SA[i] - j;
}
for (int i = 1; i <= n; ++i) VC[i] = x[y[i]];
for (int i = 1; i <= m; ++i) Sum[i] = 0;
for (int i = 1; i <= n; ++i) ++Sum[VC[i]];
for (int i = 2; i <= m; ++i) Sum[i] += Sum[i - 1];
for (int i = n; i >= 1; --i) SA[Sum[VC[i]]--] = y[i];
t = x; x = y; y = t;
x[SA[1]] = 1; p = 1;
for (int i = 2; i <= n; ++i)
x[SA[i]] = Cmp(y, SA[i], SA[i - 1], j) ? p : ++p;
}
for (int i = 1; i <= n; ++i) Rank[SA[i]] = i;
}

int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
cin >> S[i];
A[i] = S[i] - 'A' + 1;
A[2 * n - i + 2] = A[i];
}
A[n + 1] = 27;
A[n * 2 + 2] = 28;
DA(A, n * 2 + 2, 28);
int l = 1, r = n, Top = 0;
while (l <= r) {
if (S[l] != S[r]) {
if (S[l] < S[r]) {
Sout[++Top] = S[l];
++l;
}
else {
Sout[++Top] = S[r];
--r;
}
continue;
}
if (l == r) {
Sout[++Top] = S[l];
break;
}
if (Rank[l] < Rank[n * 2 - r + 2]) {
Sout[++Top] = S[l];
++l;
}
else {
Sout[++Top] = S[r];
--r;
}
}
for (int i = 1; i <= Top; ++i) {
printf("%c", Sout[i]);
if (i % 80 == 0) printf("\n");
}
return 0;
}


---恢复内容结束---

posted @ 2015-01-10 15:07  JoeFan  阅读(210)  评论(0编辑  收藏  举报