后缀数组模板

7 篇文章 0 订阅
1 篇文章 0 订阅

刘汝佳的代码会RE!!!被坑了3小时!

以下模板自带注释

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
#define maxn 100005
#define rank RANK
int n;
char str[maxn];
int cnt[maxn];
int t1[maxn],t2[maxn];
int sa[maxn];
int rank[maxn];
int height[maxn];
void build()
{
	int *x=t1,*y=t2;
	int m=26;
	for(int i=0;i<n;i++) cnt[x[i]=(str[i]-'a')]++;
	for(int i=1;i<m;i++) cnt[i]+=cnt[i-1];
	for(int i=n-1;i>=0;i--) sa[--cnt[x[i]]]=i;
	for(int k=1;k<=n;k<<=1)
	{
		int p=0;
		for(int i=n-1;i>=n-k;i--) y[p++]=i;
		for(int i=0;i<n;i++) if(sa[i]>=k) y[p++]=sa[i]-k;
		//y[i]:position of the suffix having the i-th "next k num",similar to sa
		memset(cnt,0,sizeof(cnt));
		for(int i=0;i<p;i++) cnt[x[y[i]]]++;
		for(int i=1;i<m;i++) cnt[i]+=cnt[i-1];
		for(int i=p-1;i>=0;i--) sa[--cnt[x[y[i]]]]=y[i];
		//give a higher rank to suffix with larger second keyword when having same first one
		swap(x,y);//this time,y stores the information
		p=0;
		for(int i=0;i<n;i++)
			x[sa[i]]= (!i||y[sa[i]]!=y[sa[i-1]]||y[sa[i]+k]!=y[sa[i-1]+k]) ? \
				p++:p-1;
		if(p>=n) break;
		m=p;
	}
	for(int i=0;i<n;i++) rank[sa[i]]=i;
	int k=0;
	for(int i=0;i<n;i++)
	{
		if(k) k--;
		if(rank[i]==0) continue;
		int j=sa[rank[i]-1];
		while(str[i+k]==str[j+k]) k++;
		height[rank[i]]=k;
	}
	
}
int main()
{
 	//freopen(".in","r",stdin);
 	scanf("%d",&n);
 	scanf("%s",str);
 	build();
 	for(int i=0;i<n;i++) printf("%d ",sa[i]);
 	putchar('\n');
 	for(int i=0;i<n;i++) printf("%d ",rank[i]+1);
 	putchar('\n');
 	for(int i=1;i<n;i++) printf("%d ",height[i]);
}


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值