HDU4513 完美队形II 【马拉车manacher】

click here to problem


SOL

Sorry for using English due to my computer’s error…

According to the characteristic of the Manacher Algorithm,we will cover each different sentence in the process.

So, just use another two arrays to check whether this sentence is valid.
Take down the longest length in the process.

// The HDOJ is so strange! I have to rewrite the function “min” and “max” myself…


CODE

#include
#include
#include
#include
using namespace std;
#define sf scanf
#define pf printf
const int N=2e6+10,inf=2e9;
int r[N],L[N],_r[N],t[N];
inline int _max(int a,int b){
	return a>b? a:b;
}
inline int _min(int a,int b){
	return a<b? a:b;
}

int manacher(){
	int len,k=-1;
	memset(r,0,sizeof r);
	memset(L,0,sizeof L);
	sf("%d",&len);
	
	for(int i=0;i<len;++i){
		t[++k]=inf;
		sf("%d",&t[++k]);
	}
	t[++k]=inf;
	len=k+1;
	for(int i=0;i<len;++i)_r[i]=1;
	int p=0,mx=0,ans=0;
	for(int i=0;i<len;++i){
		r[i]= mx>i ? _min(r[2*p-i],mx-i) : 1 ;
		if(r[i]==1)L[i]=t[i];
		else if(L[2*p-i]==-1){
			if(_r[2*p-i]<mx-i)_r[i]=_r[2*p-i],L[i]=-1;
			else _r[i]=r[i],L[i]=t[i-r[i]+1]==inf? t[i-r[i]+2] : t[i-r[i]+1];
		}
		else{
			L[i]=t[i-r[i]+1]==inf? t[i-r[i]+2] : t[i-r[i]+1];	
			_r[i]=r[i];
		}
		while(i-r[i]>=0&&i+r[i]<len&&t[i-r[i]]==t[i+r[i]]){
			++r[i];
			if(L[i]^(-1)){
				if(t[i+r[i]-1]!=inf){
					if(t[i-r[i]+1]<=L[i]){
						++_r[i];L[i]=t[i-r[i]+1];
						ans=_max(ans,_r[i]);	
					}
					else{
						L[i]=-1;
					}
				}
				else{
					++_r[i];
				}
			}
		}
		if(mx<i+r[i]) mx=i+r[i],p=i;	
	}
	return ans;
}
signed main(){
	int n;sf("%d",&n);
	while(n--)cout<<manacher()<<'\n';
	return 0;
}

你可能感兴趣的:(回文,manacher马拉车,字符串)