HDU 3294(manacher模板题)

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!

解析

用manacher算法求出回文半径

AC代码

#include <bits/stdc++.h>
using namespace std;

const int maxn = 3e5 + 5;
char s[maxn], ch;
int x, p_arr[maxn], len;
int R, C;

void manacher()
{
    R = C = -1;
    int r = -1, c = -1;
    for(int i = len; i >= 0; i--)
        s[i + i + 2] = s[i], s[i + i + 1] = '#';
    s[0] = '*';

    len = 2 * len + 1;
    for(int i = 1; i <= len; i++)
    {
        p_arr[i] = r > i ? min(r - i, p_arr[2 * c - i]) : 1;
        while(s[i - p_arr[i]] == s[i + p_arr[i]])
            p_arr[i]++;
        if(i + p_arr[i] > r)
            r = i + p_arr[i], c = i;
        if(p_arr[i] - 1 > R)
            R = p_arr[i] - 1, C = i;
    }
}

int main()
{
    while(scanf("%c %s", &ch, s) != EOF)
    {
        getchar();
        x = ch - 'a';
        len = strlen(s);
        for(int i = 0; i < len; i++)
            s[i] = (s[i] - x + 52 - 'a') % 26 + 'a';
        manacher();
        if(2 * R - 1 < 2)
            printf("No solution!\n");
        else
        {
            printf("%d %d\n", (C - R + 1) / 2 - 1, (C + R - 1) / 2 - 1);
            for(int i = C - R + 1; i <= C + R - 1; i++)
                if(s[i] != '*' && s[i] != '#')
                    printf("%c", s[i]);
            printf("\n");
        }
    }
    return 0;
}
发布了76 篇原创文章 · 获赞 18 · 访问量 2755

猜你喜欢

转载自blog.csdn.net/qq_43446165/article/details/103840565
今日推荐