HDU 3068 最长回文(求最长回文子串)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3068
用到了
Manacher's ALGORITHM: O(n)时间求字符串的最长回文子串 (点我)
这个算法,直接贴大牛的详解吧。#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; typedef long long ll; const int maxn = 110010; char s[maxn]; char s2[maxn*2]; int p[maxn *2]; // mx == p[id] + id , 回文右边界 // id 回文中心 void Man(){ memset(p,0,sizeof(p)); int mx = 0 ,id=0; for(int i=0;s2[i]!='\0';i++){ p[i] = mx > i ?min(p[2*id-i],mx-i ):1; while(s2[i+p[i]] == s2[i-p[i]]) p[i]++; if(p[i] + i > mx){ mx = p[i] + i; id = i; } } } int main(){ while(scanf("%s",s)!=EOF){ s2[0] = '$'; int len = strlen(s); int c = 1;//注意这里 == 1 for(int i=0;i<len;i++){ s2[c++] = '#'; s2[c++] = s[i]; } s2[c++] ='#'; s2[c] = '\0'; Man(); int ans = 1; for(int i=0;i<c;i++) ans = max(ans,p[i]); printf("%d\n",ans-1); } return 0; }