您的位置:首页 > 其它

URAL 1297 Palindrome(最长回文子串 )

2013-07-30 19:43 295 查看
这个题目现在是用manacher线性算法写的,后缀数组版本的还没实现,打算过两天搞定

还是觉得这个算发搞定回文问题既好写又快

pos*2-i这个就是求i位置关于pos的一个对称点,本质上是这样的 pos-(i-pos);

i-pos是i相对pos偏右的距离

#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
#define MIN(a,b) (a<b?a:b)
char str[2500];
char rec[2500];
int drome[2500];
int main()
{
int i,j,k;
int max_pos,pos;
while(scanf("%s",rec)!=EOF)
{
k=0;
str[k++]='@';
for(i=0;rec[i];i++)
{
str[k++]='#';
str[k++]=rec[i];
}
str[k++]='#';
str[k]=0;
drome[0]=1;
max_pos=0;
pos=0;
for(i=1;str[i];i++)
{
if(max_pos > i)
{
drome[i]=MIN(drome[pos*2-i],max_pos-i);
}
else
drome[i]=1;
for( ;str[i+drome[i]]==str[i-drome[i]];drome[i]++) ;
if(i+drome[i] > max_pos)
pos=i,max_pos=drome[i]+i;
}
max_pos=-1;
pos=0;
for(j=0;j<i;j++)
{
if(drome[j] > max_pos)
{
max_pos=drome[j];
pos=j;
}
}
//  printf("MAX:%d\n",max_pos);
max_pos;
k=pos-max_pos+1;
pos+=max_pos-1;
for(k;k<pos;k++)
if(str[k]!='#')
printf("%c",str[k]);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  manacher 算法