【bzoj1031】[JSOI2007]字符加密Cipher
*题目描述:
喜欢钻研问题的JS同学,最近又迷上了对加密方法的思考。一天,他突然想出了一种他认为是终极的加密办法
:把需要加密的信息排成一圈,显然,它们有很多种不同的读法。例如下图,可以读作:
JSOI07 SOI07J OI07JS I07JSO 07JSOI 7JSOI0把它们按照字符串的大小排序:07JSOI 7JSOI0 I07JSO JSOI07
OI07JS SOI07J读出最后一列字符:I0O7SJ,就是加密后的字符串(其实这个加密手段实在很容易破解,鉴于这是
突然想出来的,那就^^)。但是,如果想加密的字符串实在太长,你能写一个程序完成这个任务吗?
*输入:
输入文件包含一行,欲加密的字符串。注意字符串的内容不一定是字母、数字,也可以是符号等。
*输出:
输出一行,为加密后的字符串。
*样例输入:
JSOI07
*样例输出:
I0O7SJ
*提示:
对于100%的数据字符串的长度不超过100000。
*题解:
后缀数组果题。把字符串变成两倍以后对后缀进行排序,然后每一位的答案就是sa[i]的前一位字符。
*代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#ifdef WIN32
#define LL "%I64d"
#else
#define LL "%lld"
#endif
#ifdef CT
#define debug(...) printf(__VA_ARGS__)
#define setfile()
#else
#define debug(...)
#define filename ""
#define setfile() freopen(filename".in", "r", stdin); freopen(filename".out", "w", stdout);
#endif
#define R register
#define getc() (S == T && (T = (S = B) + fread(B, 1, 1 << 15, stdin), S == T) ? EOF : *S++)
#define dmax(_a, _b) ((_a) > (_b) ? (_a) : (_b))
#define dmin(_a, _b) ((_a) < (_b) ? (_a) : (_b))
#define cmax(_a, _b) (_a < (_b) ? _a = (_b) : 0)
#define cmin(_a, _b) (_a > (_b) ? _a = (_b) : 0)
char B[1 << 15], *S = B, *T = B;
inline int FastIn()
{
R char ch; R int cnt = 0; R bool minus = 0;
while (ch = getc(), (ch < '0' || ch > '9') && ch != '-') ;
ch == '-' ? minus = 1 : cnt = ch - '0';
while (ch = getc(), ch >= '0' && ch <= '9') cnt = cnt * 10 + ch - '0';
return minus ? -cnt : cnt;
}
#define maxn 400010
char str[maxn];
int c[maxn], sa[maxn], wa[maxn], wb[maxn], wv[maxn], r[maxn];
inline void getsa(R int n, R int m)
{
R int *x = wa, *y = wb, *t;
for (R int i = 0; i <= m; ++i) c[i] = 0;
for (R int i = 1; i <= n; ++i) ++c[x[i] = r[i]];
for (R int i = 1; i <= m; ++i) c[i] += c[i - 1];
for (R int i = n; i; --i) sa[c[x[i]]--] = i;
m = 0;
for (R int i = 1; i <= n; ++i) y[sa[i]] = x[sa[i - 1]] != x[sa[i]] ? ++m : m;
for (R int j = 1; m < n && j <= n; j <<= 1)
{
t = x; x = y; y = t;
for (R int i = 0; i <= m << 2; ++i) c[i] = 0;
for (R int i = 1; i <= n; ++i) ++c[x[i + j]];
for (R int i = 1; i <= m; ++i) c[i] += c[i - 1];
for (R int i = n; i; --i) y[c[x[i + j]]--] = i;
for (R int i = 0; i <= m << 2; ++i) c[i] = 0;
for (R int i = 1; i <= n; ++i) ++c[x[y[i]]];
for (R int i = 1; i <= m; ++i) c[i] += c[i - 1];
for (R int i = n; i; --i) sa[c[x[y[i]]]--] = y[i];
m = 0;
for (R int i = 1; i <= n; ++i)
y[sa[i]] = x[sa[i - 1]] == x[sa[i]] && x[sa[i - 1] + j] == x[sa[i] + j] ? m : ++m;
}
}
int main()
{
gets(str + 1);
R int len = strlen(str + 1);
for (R int i = 1; i <= len; ++i) str[i + len] = str[i];
for (R int i = 1; i <= len << 1; ++i) r[i] = str[i];
getsa(len << 1, 256);
R int num = 0;
for (R int i = 1; i <= len << 1; ++i)
if (sa[i] <= len)
printf("%c", str[sa[i] - 1 + len] );
return 0;
}