hdu3294(Manacher算法)

来源:互联网 发布:lol扫号器数据 编辑:程序博客网 时间:2024/03/29 17:27

Girls' research

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


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 babda abcd
 

Sample Output
0 2azaNo solution!
 

Author
wangjing1111
 

Source
2010 “HDU-Sailormoon” Programming Contest
 

Recommend
lcy
 
本题要求最长回文子串。首先得根据转化规则得到新字符串,可以通过类似模26的新串。然后就是处理最长回文子串的问题了,可以用Manacher算法在O(N)内解决。
#include<iostream>#include<cstdio>#include<cstring>using namespace std;int start;//*****************************************************************const int MAXN=200000+100;char str1[MAXN*2],str2[MAXN*2];//待处理字符串int num[MAXN*2];char ch[10];//将str1变成str2,如abab变成$#a#b#a#b#void init(){int i,id;str2[0]='$';str2[1]='#';for(i=0,id=2;str1[i];i++,id+=2){str2[id]=str1[i];str2[id+1]='#';}str2[id]=0;}//Manacher算法求最长回文子串,时间复杂度为O(N)int Manacher(){int i,ans=0,MxR=0,pos;for(i=1;str2[i];i++){if(MxR>i)num[i]=num[pos*2-i]<(MxR-i)?num[pos*2-i]:(MxR-i);else num[i]=1;while(str2[i+num[i]]==str2[i-num[i]])num[i]++;if(num[i]+i>MxR){MxR=num[i]+i;pos=i;}if(ans<num[i]){start=(i-num[i])/2;ans=num[i];}}return ans-1;}//*****************************************************************int main(){int i,len,dif,ans;while(~scanf("%s%s",ch,str1)){len=strlen(str1);dif='a'-ch[0];for(i=0;i<len;i++){str1[i]=str1[i]+dif<'a'?str1[i]+dif+26:str1[i]+dif;} init(); start=-1; ans=Manacher(); if(ans>1) { printf("%d %d\n",start,start+ans-1); str1[start+ans]=0; printf("%s\n",str1+start); } else  printf("No solution!\n");}return 0;}

原创粉丝点击