首页 > 代码库 > HDU3068(Manacher算法)

HDU3068(Manacher算法)

最长回文

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 18219    Accepted Submission(s): 6689


Problem Description

给出一个只由小写英文字符a,b,c...y,z组成的字符串S,求S中最长回文串的长度.
回文就是正反读都是一样的字符串,如aba, abba等
 

 

Input

输入有多组case,不超过120组,每组输入为一行小写英文字符a,b,c...y,z组成的字符串S
两组case之间由空行隔开(该空行不用处理)
字符串长度len <= 110000
 

 

Output

每一行一个整数x,对应一组case,表示该组case的字符串中所包含的最长回文长度.
 

 

Sample Input

aaaa
abab
 

 

Sample Output

4
3
 

 

Source

2009 Multi-University Training Contest 16 - Host by NIT
 
 1 //2016.10.06 2 #include <iostream> 3 #include <cstdio> 4 #include <cstring> 5  6 using namespace std; 7  8 const int N = 110005; 9 char str[N], s[N<<1];10 int a[N<<1];11 12 int manacher(char *s, int *a, int len)13 {14     a[0] = 0;15     int ans = 0, j;16     for(int i = 0; i < len; )17     {18         while(i-a[i]>0 && s[i+a[i]+1]==s[i-a[i]-1])19               a[i]++;20         if(ans < a[i])ans = a[i];21         j = i+1;22         while(j<=i+a[i] && i-a[i]!=i+i-j-a[i+i-j]){23             a[j] = min(a[i+i-j], i+a[i]-j);24             j++;25         }26         a[j] = max(i+a[i]-j, 0);27         i = j;28     }29     return ans;30 }31 32 int main()33 {34     int len;35     while(scanf("%s", str)!=EOF)36     {37         len = 2*strlen(str)+1;38         for(int i = 0; str[i] != \0; i++)39         {40             s[i+i] = \0;41             s[i+i+1] = str[i];42         }43         s[len-1] = \0;44         printf("%d\n", manacher(s, a, len));45     }46 47     return 0;48 }

 

 

HDU3068(Manacher算法)