求最长回文字串,n <= 110000.
先上模板题3068,
//http://acm.hdu.edu.cn/showproblem.php?pid=3068
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
#define N 110005
char a[N];
char b[N << 1];
int p[N << 1];
int n;
void init()
{
n = 2;
b[0] = '$', b[1] = '#';
for (int i = 0; a[i]; i++)
{
b[n++] = a[i];
b[n++] = '#';
}
}
void manacher()
{
int most_right = 0, Id, ans = 0;
for (int i = 1; i < n; i++)
{
if( most_right > i )
{
p[i] = min( p[Id*2-i], most_right - i );
// 优化的无谓比较是,例如 # a # b # c # b # a # d # a # b # c # b # a #
// 在计算右边的c所在的p[]时,因为左右的c都在maxid的范围内,
//而之前已经计算过左边的c的p[]已经计算过,根据回文串的特性(以中心对称)
//显然可以得到右边的c的p[] 就可以根据右边得到了
}
else
{
p[i] = 1;
}
while( b[i - p[i]] == b[i + p[i]])
p[i]++;
if(p[i] + i > most_right)
{
Id = i;
most_right = p[i] + i;
}
ans = ans > p[i]? ans : p[i];
}
printf("%d\n", ans - 1);
}
int main()
{
while(~scanf("%s", a))
{
init();
manacher();
}
return 0;
}
4513加了点变化,要求回文串满足从两边到中心不降。反正都是中文题= =
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
#define N 100005
int p[N*2], a[N], b[N*2];
int n;
int main()
{
int tot;
for ( scanf("%d", &tot); tot--; )
{
scanf("%d", &n);
for ( int i = 1; i <= n; i ++ )
{
scanf("%d", &a[i]);
}
b[0] = 0, b[1] = 1;
int pos = 2;
for ( int i = 1; i <= n; i++ )
{
b[pos++] = a[i];
b[pos++] = 1;
}
int mx = 0, id, ans = 0;
b[pos] = 1;
for ( int i = 1; i < pos; i++ )
{
if(mx > i)
{
p[i] = min( mx - i, p[id * 2 - i] );
}
else
{
p[i] = 1;
}
while( 1 )
{
if(b[i - p[i]] == b[i + p[i]])
{
if( b[i - p[i]] == 1 || b[i - p[i] + 2] >= b[i - p[i]])
p[i]++;
else
break;
}
else
break;
}
if( p[i] + i > mx)
{
id = i;
mx = i + p[i];
}
ans = ans > p[i]? ans : p[i];
}
printf("%d\n", ans - 1);
}
return 0;
}