HDU3294 Girls' research —— Manacher算法 输出解

题目链接:https://vjudge.net/problem/HDU-3294

Girls' research

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 3209    Accepted Submission(s): 1228

Problem Description
One day, sailormoon girls are so delighted that they intend to research about palindromic strings. Operation contains two steps:
First step: girls will write a long string (only contains lower case) on the paper. For example, "abcde", but 'a' inside is not the real 'a', that means if we define the 'b' is the real 'a', then we can infer that 'c' is the real 'b', 'd' is the real 'c' ……, 'a' is the real 'z'. According to this, string "abcde" changes to "bcdef".
Second step: girls will find out the longest palindromic string in the given string, the length of palindromic string must be equal or more than 2.
 
Input
Input contains multiple cases.
Each case contains two parts, a character and a string, they are separated by one space, the character representing the real 'a' is and the length of the string will not exceed 200000.All input must be lowercase.
If the length of string is len, it is marked from 0 to len-1.
 
Output
Please execute the operation following the two steps.
If you find one, output the start position and end position of palindromic string in a line, next line output the real palindromic string, or output "No solution!".
If there are several answers available, please choose the string which first appears.
 
Sample Input
b babd
a abcd
 
Sample Output
0 2
aza
No solution!
 
Author
wangjing1111
 
Source
 
Recommend
lcy

题解:

求最长回文子串并输出解。此题的关键在于怎么记录子串的左右两端点。

根据Manacher算法所操作的字符数组Ma[]和原串s[],找出两者下标的对应关系即可。

代码如下:

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <sstream>
#include <algorithm>
using namespace std;
typedef long long LL;
const double eps = 1e-;
const int INF = 2e9;
const LL LNF = 9e18;
const int maxn = 2e5+; char s[maxn], Ma[maxn<<];
int Mp[maxn<<];
int L, R; int Manacher(char *s, int len)
{
int ret = ;
int l = ; Ma[l++] = '$'; Ma[l++] = '#';
for(int i = ; i<len; i++)
{
Ma[l++] = s[i];
Ma[l++] = '#';
}
Ma[l] = ; int mx = , id = ;
for(int i = ; i<l; i++)
{
Mp[i] = mx>=i?min(Mp[*id-i], mx-i):;
while(Ma[i-Mp[i]-]==Ma[i+Mp[i]+]) Mp[i]++;
if(i+Mp[i]>mx)
{
mx = i+Mp[i];
id = i;
}
if(ret<Mp[i])
{
ret = Mp[i];
//第一步为求出在Ma数组上的位置, 第二步为求出在s数组,即在原串的位置
L = id-Mp[id]; L = (L+)/ - ;
R = id+Mp[id]; R = R/ - ;
}
}
return ret;
} int main()
{
char turn;
while(scanf("%c", &turn)!=EOF)
{
scanf("%s", s); getchar();
int len = strlen(s);
for(int i = ; i<len; i++) //转换字符串
{
s[i] = s[i]-turn+'a';
if(s[i]<'a') s[i] += ;
} int sum = Manacher(s, len);
if(sum<) //如果回文串长度小于二, 则无解
puts("No solution!");
else //否则输出答案
{
printf("%d %d\n", L, R);
for(int i = L; i<=R; i++)
putchar(s[i]);
putchar('\n');
}
}
}
上一篇:[ActionScript 3.0] 图片左右循环移动


下一篇:Vue2.0源码阅读笔记(三):计算属性