[APIO2014]回文串,LuoguP3649,后缀自动机+Manacher+倍增

本文介绍了一种结合后缀自动机和Manacher算法的解决方案,用于处理字符串匹配和子串出现次数的问题。通过深入理解Manacher算法,我们可以发现只有在字符串长度扩张时,本质不同的字符串才会出现。利用后缀自动机,从特定等价类开始遍历并加速查找过程,实现了高效的子串出现次数计算。

正题

      Portal

      学后缀自动机以来第一次写的题。

      强行学习Manacher之后,可以发现本质不同的字符串当len在扩张的时候才会出现,否则肯定在前面出现过。

      然后现在已知一个子串,要求它的出现次数,想到后缀自动机,我们从r前缀这个等价类开始往它的link跳,因为每跳一次就会变成原来的后缀,所一直要保证长度>=len就好了,具体过程用倍增加速。

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
using namespace std;

const int N=300010;
char temp[N],s[N<<1];
int len;
struct sam{
	int link,next[26],len;
}sam[N<<1];
int pos[N],tot,last;
int f[N<<1][20],maxlen[N<<1];
struct edge{
	int y,next;
}e[N<<1];
int first[N<<1],t[N<<1];
long long ans=0;

void insert(int c){
	int now=++tot;sam[now].len=sam[last].len+1;t[now]=1;
	while(last!=-1 && !sam[last].next[c]) sam[last].next[c]=now,last=sam[last].link;
	if(last==-1) sam[now].link=0;
	else {
		int temp=sam[last].next[c];
		if(sam[temp].len==sam[last].len+1) sam[now].link=temp;
		else{
			int np=++tot;sam[np]=sam[temp];sam[np].len=sam[last].len+1;
			sam[temp].link=sam[now].link=np;
			while(last!=-1 && sam[last].next[c]==temp) sam[last].next[c]=np,last=sam[last].link;
		}
	}
	last=now;
}

void ins(int x,int y){
	static int len=0;
	e[++len]=(edge){y,first[x]};first[x]=len;
}

void dfs(int x){
	for(int i=first[x];i!=0;i=e[i].next){
		int y=e[i].y;
		f[y][0]=x;
		for(int k=1;k<=19;k++) f[y][k]=f[f[y][k-1]][k-1];
		dfs(y);t[x]+=t[y];
	}
}

void solve(int l,int r){
	int now=pos[r];
	for(int i=19;i>=0;i--) if(sam[f[now][i]].len>=r-l+1) now=f[now][i];
	ans=max(ans,1ll*t[now]*(r-l+1));
}

void Manacher(){
	int op=0,mx=0;
	s[0]='@';for(int i=1;i<=len;i++) s[i*2-1]='#',s[i*2]=temp[i];
	s[len*2+1]='#',s[len*2+2]='*';len=len*2+1;
	for(int i=1;i<=len;i++){
		if(i<mx) maxlen[i]=min(mx-i,maxlen[2*op-i]);
		while(s[i-maxlen[i]-1]==s[i+maxlen[i]+1]){
			maxlen[i]++;
			if((i-maxlen[i])%2==1) solve((i-maxlen[i]+1)/2,(i+maxlen[i]-1)/2);
		}
		if(i+maxlen[i]>mx) mx=i+maxlen[i],op=i;
	}
}

int main(){
	scanf("%s",temp+1);len=strlen(temp+1);
	sam[0].link=-1;sam[0].len=0;
	for(int i=1;i<=len;i++) pos[i]=tot+1,insert(temp[i]-'a');
	for(int i=1;i<=tot;i++) ins(sam[i].link,i);
	dfs(0);Manacher();
	printf("%lld\n",ans);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值