1. 程式人生 > >【hdu3294】Girls' research——manacher

【hdu3294】Girls' research——manacher

eps appear abcd not 輸入 osi sam n! marked

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! 其實這道題本質上就是一道裸的manacher,我們知道替換字母並不會影響它是不是回文,該是回文的還是,不是的也肯定依然不是,因此我們可以先跑一遍manacher,然後再進行字母的轉換(這樣可以避免對不是最長回文的字母進行無謂的轉換)。 關於起始點和終止點,分別是(a-p[a]+2)/2-1(a+p[a]-2)/2-1。其中a是最長回文串的對稱軸,至於這是為什麽希望你能自己推導一下。
最後是這道題最特殊的地方——字母替換: 首先要輸入的是一個數組,這樣讀到EOF時才會退出循環。 然後int k為c[0]-‘a‘,即向前進幾個單位,用s[i]-‘a‘-k來表示是第幾個字母,不過這樣得到的可能是一個負數,所以應該是(s[i]-‘a‘-k+26)%26+‘a‘。 具體實現細節看代碼。 技術分享
#include<cstdio>
#include<cstring>
#include<iostream>
const int maxn=400010;
using namespace std;
char c[2],s[maxn];
int pos,len,p[maxn],a;
int main()
{
    while(~scanf("%s %s",c,s))
    {
        len=strlen(s);pos=0;a=0;
        for(int i=len;i>=0;i--)
        {
            s[i*2+2]=s[i];
            s[i*2+1]=#;
        }
        s[0]=&;p[0]=0;
        for(int i=2;i<len*2+1;i++)
        {
            if(pos+p[pos]>i)p[i]=min(p[pos*2-i],pos+p[pos]-i);
            else p[i]=1;
            while(s[i+p[i]]==s[i-p[i]])p[i]++;
            if(pos+p[pos]<i+p[i])pos=i;
            if(p[a]<p[i])a=i;
        }
        if(p[a]-1<2)printf("No solution!\n");
        else{
            printf("%d %d\n",(a-p[a]+2)/2-1,(a+p[a]-2)/2-1);
            int k=c[0]-a;
            for(int i=a-p[a]+2;i<=a+p[a]-2;i+=2)printf("%c",(s[i]-a-k+26)%26+a);
            printf("\n");
        }
    }
    return 0;
}
View Code

【hdu3294】Girls' research——manacher