Description
喜欢钻研问题的JS 同学,最近又迷上了对加密方法的思考。一天,他突然想出了一种他认为是终极的加密办法:把需要加密的信息排成一圈,显然,它们有很多种不同的读法。例如下图,可以读作:
JSOI07 SOI07J OI07JS I07JSO 07JSOI 7JSOI0把它们按照字符串的大小排序:07JSOI 7JSOI0 I07JSO JSOI07 OI07JS SOI07J读出最后一列字符:I0O7SJ,就是加密后的字符串(其实这个加密手段实在很容易破解,鉴于这是突然想出来的,那就^^)。但是,如果想加密的字符串实在太长,你能写一个程序完成这个任务吗?
Input
输入文件包含一行,欲加密的字符串。注意字符串的内容不一定是字母、数字,也可以是符号等。
Output
输出一行,为加密后的字符串。
Sample Input
JSOI07
Sample Output
I0O7SJ
题解
将原串复制一遍,求出后缀数组便可以很容易得出答案。
后缀数组的模板你需要一个善良的学长…
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<memory>
#include<vector>
#include<deque>
#include<cmath>
#include<ctime>
#include<queue>
#include<list>
#include<map>
#include<set>
#define max(x,y) ((x)>(y)?(x):(y))
#define min(x,y) ((x)<(y)?(x):(y))
#define F(i,j,n) for(register int i=j;i<=n;i++)
#define D(i,j,n) for(register int i=j;i>=n;i--)
#define ll long long
#define db double
using namespace std;
inline void in(int &x);
inline void in(ll &x);
const int N = 100000 + 10 << 1;
char ch[N];
int a[N], n, k;
int v[N], sa[2][N], rank[2][N];
void init(){
scanf("%s", ch + 1);
n = strlen(ch + 1);
for(int i = 1; i <= n; i++){
a[i] = (int) ch[i];
a[i+n] = a[i];
ch[i+n] = ch[i];
}
n <<= 1;
}
void calsa(int *sa1, int *rank1, int *sa2, int *rank2){
for(int i = 1; i <= n; i++) v[rank1[sa1[i]]] = i;
for(int i = n; i >= 1; i--)
if(sa1[i] > k)
sa2[v[rank1[sa1[i]-k]]--] = sa1[i] - k;
for(int i = n - k + 1; i <= n; i++)
sa2[v[rank1[i]]--] = i;
for(int i = 1; i <= n; i++)
rank2[sa2[i]] = rank2[sa2[i-1]]+(rank1[sa2[i-1]]!=rank1[sa2[i]]||rank1[sa2[i-1]+k]!=rank1[sa2[i]+k]);
}
void work(){
//printf("%s\n", ch+1);
int p = 0, q = 1;
for(int i = 1; i <= n; i++) v[a[i]]++;
for(int i = 1; i <= 256; i++) v[i] += v[i-1];
for(int i = 1; i <= n; i++) sa[p][v[a[i]]--] = i;
for(int i = 1; i <= n; i++) rank[p][sa[p][i]] = rank[p][sa[p][i-1]] + (a[sa[p][i-1]] != a[sa[p][i]]);
k = 1;
while(k < n){
calsa(sa[p], rank[p], sa[q], rank[q]);
p ^= 1; q ^= 1; k <<= 1;
}
for(int i = 1; i <= n; i++){
if(sa[p][i] <= n/2)
printf("%c", ch[sa[p][i]+n/2-1]);
}
}
int main(){
init();
work();
return 0;
}
inline void in(int &x){
x = 0; int 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 - '0'; ch = getchar();}
x *= f;
}
inline void in(ll &x){
x = 0; ll 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 - '0'; ch = getchar();}
x *= f;
}