ACM学习感悟——ACdream字符串专场F(manacher)

Problem Description

正如大家知道的,女神喜欢字符串,而在字符串中,女神最喜欢回文字符串,但是不是所有的字符串都是回文字符串,但是有一些字符串可以进行“求导”来变成回文字符串。

字符串中只包含小写字母。
求导过程如下,C++:

string dif(const string x)
{
    if(x.length()<=1)
        return "";
    string res="";
    for(int i=1;i<x.length();++i)
        res+=abs(x[i]-x[i-1])+'a';
    return res;
}

C:

void dif(char*x,char*res)//注意有可能会溢出
{
    if(x[0]==0||x[1]==0)
    {
        res[0]=0;
        return;
    }
    int len=1;
    for(int i=1;x[i];++i,++len)
        res[i-1]=abs(x[i]-x[i-1])+'a';
    res[len-1]=0;
}

例如"aa"的导字符串是“a",”aab“的导字符串是"ab","aacfwssg"的导字符串是"acdream"。

那么给定一个字符串,请判断在它各阶导字符串中,最长的回文串是多长?

二阶导字符串即为导字符串的导字符串。

n阶导字符串即为n-1阶导数的导字符串。

Input
多组数据,每组数据包括一个字符串s(1<=|s|<=1000)
Output
对于每组数据,输出一个整数
Sample Input
abcd
abcba
acdream
Sample Output
3
5
3
Hint

样例一,求一次导字符串后为”aaa“,最长回文子串就是本身,所以长度为3

样例二,本身就是回文串,因此,输出本身长度即可

样例三,acdream->cbonem->bnbji->mmib->aeh->ed->b

最长回文串长度分别为1,1,3,2,1,1,1,因此输出3

起始我写这个只是想记得模板罢了,好吧,一道manacher算法的裸题,虾米那直接上代,有一点注意的就是p数组要开的大一点,不然会越界,因为预处理会将字符扩大两倍。

AC代码:

//  Created by  CQUWEL
//  Copyright (c) 2015年 CQUWEL. All rights reserved.
//
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <algorithm>
#include <numeric>
#include <functional>
#define INF 0x3f3f3f3f
#define cir(i,a,b)  for (int i=a;i<=b;i++)
#define CIR(j,a,b)  for (int j=a;j>=b;j--)
#define CLR(x) memset(x,0,sizeof(x))
typedef long long  ll;
using namespace std;
string s,tt;
int p[1010*3];
int nn;

string dif(string &x){
	if (x.length()<=1)
		return "";
	string res="";
    for(int i=1;i<x.length();++i)
        res+=abs(x[i]-x[i-1])+'a';
    return res;
}

void preprocess(string &x){
	s[0]='@';s[1]='#';nn=2;
	for (int i=0;x[i];i++){
		s[nn++]=x[i];
		s[nn++]='#';
//		cout << "s"<<endl;
	}
	s[nn]='\0'; 
}

int manacher(string &x){
	preprocess(x);
	int mxl=0,id=0;
	for (int i=1;i<nn;i++){
		if (mxl>i) p[i]=min(mxl-i,p[2*id-i]);
		else p[i]=1;
		while (s[i-p[i]]==s[i+p[i]]) p[i]++;
		if (mxl<p[i]+i) mxl=p[i]+i,id=i; 
	}
	int ret=0;
	for (int i=1;i<nn;i++) ret=max(ret,p[i]);
	return ret-1;                                      //这里要注意!!!!
}
int main()
{
	while (getline(cin,tt)){
		int ans=0;
//		cout << dif(tt);
//		preprocess(tt);
//		for (int i=0;s[i];i++) cout << s[i];
		int l=tt.size();
		if (l==0){
			cout << "0\n";
			continue;
		}                                  //这里只是放置有空串,不过一般题目是不会给空串的。
		while (ans<tt.size()){
			ans=max(ans,manacher(tt));
//			cout << tt << "||" << ans <<endl; 
			tt=dif(tt);
			if (tt.size()<=ans) break;				
		}
		cout << ans << endl;
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值