題目連接:http://acm.hdu.edu.cn/showproblem.php?pid=3068
php
用到了ios
#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; }