[BZOJ2342] [Shoi2011]双倍回文(manacher)

传送门

 

manacher......

先跑一边manacher是必须的

然后枚举双倍回文串的对称轴x

把这个双倍回文串分成4段,w wR w wR

发现,只有当 y <= x + p[x] / 2 && y - p[y] <= x 时,y最大才是最优解

也就是y在第三段,并且以y为中心的回文串要扩展到x的或左边,并且y的回文串要被x的包在里面

那么 (y-x) * 4 中最大的就是答案

我们不妨按照 y - p[y] 排序y,枚举x,依次添加y进入set,从set中找最大的 y <= x + p[x] / 2

 

边界讨论恶心至极

#include <set>
#include <cstdio>
#include <algorithm>
#define min(x, y) ((x) < (y) ? (x) : (y))
#define max(x, y) ((x) > (y) ? (x) : (y))
#define N 1100000

int n, pos, maxright, ans;
int p[N], f[N];
char s[N];
std::set <int> S;
std::set <int> :: iterator it;

struct node
{
	int id, p;
}a[N];

inline bool cmp(node x, node y)
{
	return x.p < y.p;
}

inline void manacher()
{
	int i;
	s[0] = '$', s[n * 2 + 1] = '#';
	for(i = n; i >= 1; i--) s[i * 2] = s[i], s[i * 2 - 1] = '#';
	for(i = 1; i <= n * 2 + 1; i++)
	{
		p[i] = 1;
		if(i <= maxright)
			p[i] = min(p[pos * 2 - i], maxright - i + 1);
		while(s[i - p[i]] == s[i + p[i]]) p[i]++;
		if(maxright < i + p[i] - 1)
		{
			pos = i;
			maxright = i + p[i] - 1;
		}
	}
	for(i = 1; i <= n; i++) f[i] = (p[i * 2 - 1] - 1) / 2;
}

int main()
{
	int i, j;
	scanf("%d", &n);
	scanf("%s", s + 1);
	manacher();
	for(i = 1; i <= n; i++) a[i].id = i, a[i].p = i - f[i];
	std::sort(a + 1, a + n + 1, cmp);
	j = 1;
	for(i = 1; i <= n; i++)
	{
		while(a[j].p <= i && j <= n)
			S.insert(a[j].id), j++;
		it = S.upper_bound(i + f[i] / 2);
		if(it == S.begin()) continue;
		it--;
		ans = max(ans, (*it - i) * 4);
	}
	printf("%d\n", ans);
	return 0;
}

  

posted @ 2017-09-11 09:12  zht467  阅读(164)  评论(0编辑  收藏  举报