欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

后缀数组个人理解

程序员文章站 2024-03-15 14:19:17
...
#include<bits/stdc++.h>
#define MAXN 1000005
using namespace std;

int tong[MAXN],sa[MAXN],tp[MAXN],rank[MAXN],n,m;
char a[MAXN];

int get(char c) {
	if(c >= '0' && c <= '9') return c - '0' + 1;
	if(c >= 'A' && c <= 'Z') return c - 'A' + 11;
	return c - 'a' + 37;
}

void Debug(){
	cout<<"下标   :";for(int i = 1 ; i <= n ; i++)cout<<i<<" ";
	cout<<endl;
	cout<<"sa   :";for(int i = 1 ; i <= n ; i++)cout<<sa[i]<<" ";
	cout<<endl;
	cout<<"rank   :";for(int i = 1 ; i <= n ; i++)cout<<rank[i]<<" ";
	cout<<endl;
	cout<<"tp   :";for(int i = 1 ; i <= n ; i++)cout<<tp[i]<<" ";
	cout<<endl;
	cout<<endl<<endl;
}

void rsort(){
	for(int i = 0 ; i <= m ; i++)tong[i] = 0;
	for(int i = 1 ; i <= n ; i++)tong[rank[i]]++;
	for(int i = 1 ; i <= m ; i++)tong[i] += tong[i - 1];
	for(int i = n ; i >= 1 ; i--){
			sa[tong[rank[tp[i]]]--] = tp[i];
	}
}

void init(){
	scanf("%s" , a + 1);n = strlen(a + 1);m = 62;
	for(int i = 1 ; i <= n ; i++)rank[i] = get(a[i]) , tp[i] = i;
	rsort();
}

void solve(){
	for(int w = 1 , p = 0 ; w <= n ; w = (w + w) , m = p , p = 0){
		for(int i = n - w + 1 ; i <= n ; i++)tp[++p] = i;
		for(int i = 1 ; i <= n ; i++)if(sa[i] > w)tp[++p] = sa[i] - w;
		rsort();
		swap(rank , tp);
		rank[sa[1]] = p = 1;
		for(int i = 2 ; i <= n ; i++)
		rank[sa[i]] = (tp[sa[i]] == tp[sa[i - 1]] && tp[sa[i] + w] == tp[sa[i - 1] + w]) ? p : ++p;		
		if(p == n)break;
	}
	for(int i = 1 ; i <= n ; i++)cout<<sa[i]<<" ";
}

int main(){
	init();
	solve();
}

后缀数组个人理解

相关标签: 重要 后缀数组