跳到正文

题解

《P8631 [蓝桥杯 2015 国 AC] 切开字符串》解题报告

daduoli约 4 分钟
原文

这是 2026年2月4日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2026年2月4日
更新
2026年2月4日
篇幅
约 4 分钟
题目
P8631

版本

  1. v2当前
  2. v1

水一下咕值。

首先对于本质不同正回文串是naive的,因为要奇数,所以我们去掉偶数的,然后又因为一个串的回文串个数是 O(n)O(n) 级别的,所以,我们每次拓展新的串的时候丢到哈希里面去判一下就好了。

而对于本质不同非正回文串,我们就用本质不同的串的数量减去本质不同正回文串数量即可。

对于后缀本质不同正回文串和上面的问题同样,而对于后缀本质不同的串的数量,直接给他丢到后缀自动机上,动态维护本质不同串即可。

具体的在后缀自动机上,一个节点的最大长度为 a[u].lena[u].len ,我们动态维护 a[u].len−a[fa].lena[u].len-a[fa].len 就是答案了。

时间复杂度 O(n)O(n),空间复杂度 O(n∣S∣)O(n|S|)。 ∣S∣|S| 为字符集大小

C++
#include<bits/stdc++.h>
typedef long long LL;

using namespace std;
const int MAXN=2e5+10,bas=13331,P=993244853;
int n;
LL sum[MAXN],res;
char ch[MAXN];
struct ver {
	int fa,len,c[26];
};
struct suffix_automaton {
	int cnt=1,lt=1;
	ver a[MAXN];
	void insert(int x) {
		int u=lt,nw=++cnt;
		lt=nw;
		a[nw].len=a[u].len+1; 
		while(u&&!a[u].c[x]) {
			a[u].c[x]=nw;
			u=a[u].fa;
		}
		if(!u) a[nw].fa=1,res+=a[nw].len;
		else {
			int t=a[u].c[x];
			if(a[u].len+1==a[t].len) a[nw].fa=t,res+=a[nw].len-a[t].len;
			else {
				++cnt;
				res-=a[t].len-a[u].len;
				a[cnt]=a[t];
				a[cnt].len=a[u].len+1;
				++res;
				while(u&&a[u].c[x]==t) {
					a[u].c[x]=cnt;
					u=a[u].fa;
				}
				a[t].fa=a[nw].fa=cnt;
				res+=a[t].len+a[nw].len-2*a[cnt].len;
			}
		}
	}
}T;
LL pw[MAXN],ha[MAXN],f[MAXN],pre[MAXN],g[MAXN];
unordered_map<int,int> id;
void work() {
	for(int i=1;i<=n;++i) {
		ha[i]=ha[i-1]*bas%P+(ch[i]-'a'+1);
	}
	int mid=0,r=0;
	id.clear();
	memset(pre,0,sizeof(pre));
	for(int i=1;i<=n;++i) {
		f[i]=1;
		LL ls=(ha[i]-ha[i-1]*bas%P+P)%P;
		if(!id[ls]) {
			id[ls]=1;
			++pre[i];
		}
		if(i<=r) f[i]=min(f[mid-(i-mid)],(LL)r-i+1);
		while(i-f[i]>0&&i+f[i]<=n&&ch[i-f[i]]==ch[i+f[i]]) {
			LL ls=(ha[i+f[i]]-ha[i-1]*pw[f[i]+1]%P+P)%P;
			if(!id[ls]) {
				id[ls]=1;
				++pre[i+f[i]];
			}
			++f[i];
		}
		if(i+f[i]-1>r) mid=i,r=i+f[i]-1;
	}
	for(int i=1;i<=n;++i) {
		pre[i]+=pre[i-1];
	}
}
int main () {
	scanf("%d",&n);
	scanf("%s",ch+1);
	for(int i=n;i>=1;--i) {
		T.insert(ch[i]-'a');
		sum[i]=res;
	}
	pw[0]=1;
	for(int i=1;i<=n;++i) pw[i]=pw[i-1]*bas%P;
	work();
	for(int i=1;i<=n;++i) g[i]=pre[i];
	for(int i=1;i<=n/2;++i) swap(ch[i],ch[n-i+1]);
	work();
	LL ans=0;
	for(int i=1;i<=n;++i) {
		ans=max(ans,g[i]*(sum[i+1]-pre[n-i]));
	}
	printf("%lld\n",ans);
	return 0;
}