最長迴文(hdu3068 manacher演算法)
阿新 • • 發佈:2018-11-27
Problem Description 給出一個只由小寫英文字元a,b,c...y,z組成的字串S,求S中最長迴文串的長度.
Input 輸入有多組case,不超過120組,每組輸入為一行小寫英文字元a,b,c...y,z組成的字串S
Output 每一行一個整數x,對應一組case,表示該組case的字串中所包含的最長迴文長度.
Sample Input aaaa abab
Sample Output 4 3
|
詳細說明看原文部落格。
轉載請註明出自 https://www.felix021.com/blog/read.php?2040
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; const int maxm = 110000 + 10; char s[2*maxm]; int p[2*maxm]; int main() { while(scanf("%s",s)!=EOF) { int id = 0,mx = 0,maxlen = 0; int len = strlen(s); memset(p,0,sizeof(p)); for (int i=len;i>=0;i--) { s[i+i+2] = s[i]; s[i+i+1] = '#'; } s[0] = '*'; for (int i=2;i<=2*len+1;i++) { p[i] = mx > i ? min(p[2*id-i],mx-i) : 1; while (s[i+p[i]]==s[i-p[i]]) p[i]++; if (i+p[i]>mx) { mx = i + p[i]; id = i; } if (maxlen<p[i]) maxlen = p[i]; } printf("%d\n",maxlen-1); } return 0; }