P4051 [JSOI2007]字符加密(后缀数组)

题目链接
思路:将字符串扩大两倍然后再用后缀数组排序后得出的sa数组判断得出答案

#include <iostream>
#include <stdio.h>
#include <cstring>
#include <algorithm>
using namespace std;
#define Max_N 200010
#define F(x) ((x)/3+((x)%3==1?0:tb))
#define G(x) ((x)<tb?(x)*3+1:((x)-tb)*3+2) 
int wa1[Max_N*3], wb1[Max_N*3], wv1[Max_N*3], ws1[Max_N*3]; 
int c0(int *r, int a, int b)  
{
	return r[a] == r[b] && r[a+1] == r[b+1] && r[a+2] == r[b+2];
}
 
int c12(int k, int *r, int a, int b) 
{
	if(k == 2) return r[a] < r[b] || r[a] == r[b] && c12(1, r, a+1, b+1); 
    else return r[a] < r[b] || r[a] == r[b] && wv1[a+1] < wv1[b+1];
}
    
 void sort(int *r, int *a, int *b, int n, int m) 
 { 
	int i; 
	for (i = 0; i < n; i++) wv1[i] = r[a[i]]; 
	for (i = 0; i < m; i++) ws1[i] = 0; 
	for (i = 0; i < n; i++) ws1[wv1[i]]++; 
	for (i = 1; i < m; i++) ws1[i] += ws1[i-1]; 
	for (i = n-1; i >= 0; i--) b[--ws1[wv1[i]]] = a[i]; 
	return; 
 }
void dc3(int *r, int *sa, int n, int m)
{
	int i, j, *rn = r + n, *san = sa + n,ta = 0,tb = (n + 1) / 3,tbc = 0,p; 
    r[n] = r[n+1] = 0; 
    for (i = 0; i < n; i++) if (i % 3 != 0) wa1[tbc++] = i; 
    sort(r+2, wa1, wb1, tbc, m); 
    sort(r+1, wb1, wa1, tbc, m); 
    sort(r, wa1, wb1, tbc, m); 
    for (p = 1,rn[F(wb1[0])] = 0,i = 1;i < tbc; i++) 
    rn[F(wb1[i])] = c0(r, wb1[i-1], wb1[i]) ? p - 1 : p++; 
    if (p < tbc) dc3(rn, san, tbc, p); 
    else for (i = 0; i < tbc; i++) san[rn[i]] = i;
    for (i = 0; i < tbc; i++) if (san[i] < tb) wb1[ta++] = san[i] * 3; 
    if (n % 3 == 1) wb1[ta++] = n - 1; 
    sort(r, wb1, wa1, ta, m); 
    for (i = 0; i < tbc; i++) wv1[wb1[i] = G(san[i])] = i; 
    for (i = 0, j = 0, p = 0; i < ta && j < tbc; p++) 
    sa[p] = c12(wb1[j] % 3, r, wa1[i], wb1[j]) ? wa1[i++] : wb1[j++]; 
    for(; i < ta; p++) sa[p] = wa1[i++]; 
    for(; j < tbc; p++) sa[p] = wb1[j++]; 
    return; 
}
// str sa 都要开三倍的;
void da(int str[], int sa[], int rank1[], int height1[], int n, int m)
{
	for (int i = n; i < n*3; i++)
		str[i] = 0;
	dc3(str, sa, n+1, m);
	int i, j, k = 0;
	for (i = 0; i <= n; i++) rank1[sa[i]] = i;
	for (i = 0; i < n; i++)
	{
		if (k) k--;
		j = sa[rank1[i] - 1];
		while (str[i+k] == str[j+k]) k++;
		height1[rank1[i]] = k;
	}
	return;
}
int str[3*Max_N];
int sa[3*Max_N]; //sa[i]表示将所有后缀排序后第i小的后缀的编号。
int rank1[3*Max_N];//rank1[i]表示后缀i的排名。 
int height1[3*Max_N];
char s[Max_N];
int main()
{
	/*char buf[100];
	cin >> buf;
	int n = strlen(buf);
	//cout << n << endl;
	int m = 128;
	for (int i = 0; i < strlen(buf); i++)
		str[i] = int(buf[i]);
	str[n] = 0;
	da(str, sa, rank1, height1, n, m);
	for (int i = 0; i <= n; i++)
		cout << sa[i] << endl;
	return 0;*/
	scanf("%s",s);
	int n=strlen(s);
	int t=n*2;
	for(int i=n;i<t;i++)
	{
		s[i]=s[i-n];
	}
	for(int i=0;i<t;i++)
	{
		str[i]=int(s[i]);
	}
	str[t]=0;
	da(str, sa, rank1, height1, t, 256);
	
	for(int i=0;i<=t;i++)
	{
		if(sa[i]<n)
		{
			printf("%c",s[sa[i]+n-1]);
		}
	}
	printf("\n");
		
 
}
posted @ 2020-10-11 15:15  Ldler  Views(52)  Comments(0Edit  收藏  举报