吉哥系列故事——完美队形II-(Manacher算法)
作者:互联网
题目链接:点击进入
题目
题意
求最长回文子序列,同时要求这个回文子序列从中间向两边非严格递减
思路
Manacher算法,在预处理的时候需要用不会影响题目的数字(负数和0等)来组成新的序列。
同时扩展回文子序列时需要多一句 str[i-p[i]]<=str[i-p[i]+2] 来保证从中点向两边非严格递减
(+2是因为相邻的数是预处理时添加的负数或0,不会影响原串的回文判定)
代码
#include<iostream>
#include<string>
#include<map>
//#include<unordered_map>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<fstream>
#include<stack>
#define X first
#define Y second
#define INF 0x3f3f3f3f
#define P pair<int,int>
using namespace std;
typedef long long ll;
const double eps=0.01;
const int N=1010;
const int maxn=1e6+10;
const int mod=1000000007;
int t,n,p[maxn],cnt,len;
int str[maxn],s[maxn];
void Manacher()
{
int l=0;
str[l++]=-1;
str[l++]=0;
for(int i=0;i<len;i++)
{
str[l++]=s[i];
str[l++]=0;
}
int mx=0,di=0;
for(int i=0;i<l;i++)
{
if(i<mx) p[i]=min(p[2*di-i],mx-i);//i 在最远回文距离之内
else p[i]=1; //i 在最远回文距离之外
//左端点为'$',右端点为'\0',不需要边界判断
//更新最大半径
while(str[i+p[i]]==str[i-p[i]]&&str[i-p[i]]<=str[i-p[i]+2]) p[i]++;
//如果最远半径增大,更新半径边界
if(i+p[i]>mx)
{
mx=p[i]+i;
di=i;
}
}
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&s[i]);
len=n;Manacher();
int ans=0;
for(int i=0;i<2*len+4;i++)
ans=max(ans,p[i]-1);
printf("%d\n",ans);
}
return 0;
}
标签:const,int,Manacher,II,maxn,str,include,吉哥,define 来源: https://blog.csdn.net/Cosmic_Tree/article/details/114152195