hdu 3068 4513 manacher

求最长回文字串,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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值