跳到正文

题解

题解:P5555 秩序魔咒

Ricky214365约 5 分钟
原文
文章信息与版本

文章信息

收录
2026年2月3日
更新
2026年2月3日
篇幅
约 5 分钟
题目
P5555

版本

  1. v1当前

题意

给定两个字符串,求最长公共回文子串的长度和本质不同的最长公共回文子串个数。

解法

考虑单个字符串的所有本质不同的回文子串,这可以在跑 Manacher 每次暴力向后拓展时顺便求出,hash 后放到 map 里存着,再在第二个串上跑一遍 Manacher 遇到 map 中存着的就取出来统计答案即可。

本质不同的回文子串个数是 O(n)O(n),故算法时间复杂度为 O(nlog⁡n)O(n\log{n}),可以通过本题。

注意这道题卡单哈希。

代码

C++
#include<bits/stdc++.h>
using namespace std;
int n,m;
string a;
char s[1000006];
int d[1000006];
long long hash1[1000006],mod1=1e9+7,mul1=1236547;
long long mpow1[1000006];
long long hash2[1000006],mod2=1e8+7,mul2=8593757;
long long mpow2[1000006];
map<pair<long long,long long>,int> ma;
inline long long get_hash1(int l,int r){
	if(l)return (hash1[r]-hash1[l-1]*mpow1[r-l+1]%mod1+mod1)%mod1;
	return hash1[r];
}
inline long long get_hash2(int l,int r){
	if(l)return (hash2[r]-hash2[l-1]*mpow2[r-l+1]%mod2+mod2)%mod2;
	return hash2[r];
}
int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cin>>n>>m;
	cin>>a;
	for(int i=0;i<a.length();i++){
		s[i*2]='#';
		s[i*2+1]=a[i];
		s[i*2+2]='#';
	}
	mpow1[0]=1;
	for(int i=0;i<=n*2;i++){
		if(i)hash1[i]=(hash1[i-1]*mul1+s[i])%mod1;
		else hash1[i]=s[i];
		mpow1[i+1]=mpow1[i]*mul1%mod1;
	}
	mpow2[0]=1;
	for(int i=0;i<=n*2;i++){
		if(i)hash2[i]=(hash2[i-1]*mul2+s[i])%mod2;
		else hash2[i]=s[i];
		mpow2[i+1]=mpow2[i]*mul2%mod2;
	}
	for(int i=0,l=0,r=-1;i<=2*n;i++){
		int k;
		if(i>r)k=1;
		else k=min(d[l+r-i],r-i+1);
		while(0<=i-k && i+k<2*a.length()+1 && s[i-k]==s[i+k]){
			ma[{get_hash1(i-k,i+k),get_hash2(i-k,i+k)}]=k;
			k++;
		}
		d[i]=k--;
		if(i+k>r){
			r=i+k;
			l=i-k;
		}
	}
	cin>>a;
	for(int i=0;i<a.length();i++){
		s[i*2]='#';
		s[i*2+1]=a[i];
		s[i*2+2]='#';
	}
	mpow1[0]=1;
	for(int i=0;i<=m*2;i++){
		if(i)hash1[i]=(hash1[i-1]*mul1+s[i])%mod1;
		else hash1[i]=s[i];
		mpow1[i+1]=mpow1[i]*mul1%mod1;
		d[i]=0;
	}
	mpow2[0]=1;
	for(int i=0;i<=m*2;i++){
		if(i)hash2[i]=(hash2[i-1]*mul2+s[i])%mod2;
		else hash2[i]=s[i];
		mpow2[i+1]=mpow2[i]*mul2%mod2;
	}
	int ans1=0,ans2=0;
	for(int i=0,l=0,r=-1;i<=2*m;i++){
		int k;
		if(i>r)k=1;
		else k=min(d[l+r-i],r-i+1);
		while(0<=i-k && i+k<2*a.length()+1 && s[i-k]==s[i+k]){
			pair<long long,long long> x={get_hash1(i-k,i+k),get_hash2(i-k,i+k)};
			if(ma.find(x)!=ma.end()){
				int y=ma[x];
				if(y>ans1){
					ans1=y,ans2=1;
				}
				else if(y==ans1)ans2+=1;
				ma[x]=0;
			}
			k++;
		}
		d[i]=k--;
		if(i+k>r){
			r=i+k;
			l=i-k;
		}
	}
	cout<<ans1<<' '<<ans2<<'\n';
	return 0;
}
原文