Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P2870 [USACO07DEC]Best Cow Line G

P2870 [USACO07DEC]Best Cow Line G

考虑贪心,对于两侧不同的字符,直接选择更小的。对于不同的,选择后缀或者前缀小的,所以用将字符串反转后接在原串后面,用后缀数组排序。

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <cstdio>
using namespace std;
template <class Type>
void read (Type &x)
{
bool flag = false;
char c;
while ((c = getchar()) < '0' || c > '9')
flag |= c == '-';
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 3) + (x << 1) + c - '0';
if (flag) x = ~x + 1;
}
template <class Type, class ...rest>
void read (Type &x, rest &...y) { read(x), read(y...); }
template <class Type>
void write (Type x)
{
if (x < 0) putchar('-'), x = ~x + 1;
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
const int N = 1e6 + 10;
char str[N];
int n, m, sa[N], rnk[N], ht[N], c[N], x[N], y[N];
void bucsort ()
{
for (int i = 1; i <= m; ++i) c[i] = 0;
for (int i = 1; i <= n; ++i) ++c[x[i]];
for (int i = 1; i <= m; ++i) c[i] += c[i - 1];
for (int i = n; i; --i) sa[c[x[y[i]]]--] = y[i];
}
void init ()
{
for (int i = 1; i <= n; ++i)
x[i] = str[i] - 'A' + 1, y[i] = i, sa[i] = 0;
bucsort();
for (int k = 1; k <= n; k <<= 1)
{
int cnt = 0;
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;
bucsort();
for (int i = 1; i <= n; ++i) y[i] = x[i];
x[sa[1]] = cnt = 1;
for (int i = 2; i <= n; ++i)
x[sa[i]] = cnt += (y[sa[i]] ^ y[sa[i - 1]]) || (y[sa[i] + k] ^ y[sa[i - 1] + k]);
if ((m = cnt) == n) break;
}
for (int i = 1; i <= n; ++i) rnk[sa[i]] = i;
for (int i = 1, k = 0; i <= n; ++i)
{
int j = sa[rnk[i - 1]];
if (k) --k;
while (str[i + k] == str[j + k]) ++k;
ht[rnk[i]] = k;
}
}
int main ()
{
read(n);
for (int i = 1; i <= n; ++i)
{
char c = getchar();
while (c < 'A' || c > 'Z') c = getchar();
str[i] = str[2 * n + 2 - i] = c;
}
str[n + 1] = 'Z' + 1;
n = n << 1 | 1, m = 27;
init();
n >>= 1;
for (int t = 0, l = 1, r = n; l <= r; (++t % 80 == 0) && puts(""))
putchar(str[rnk[l] < rnk[2 * n + 2 - r] ? l++ : r--]);
return 0;
}