HDU - 3068 最长回文(manacher)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3068
求最长回文串,manacher算法。具体可以看转载的blog,代码如下:
#include <iostream> #include <cstdio> #include <string> #include <cstring> #include <algorithm> using namespace std; char line[220020],s[220020]; int Mp[110010*2]; void Manacher(int len){ int l = 0; s[l++] = '$'; s[l++] = '#'; for(int i = 0;i < len;i ++){ s[l++] = line[i]; s[l++] = '#'; } int id = 0, mx = 0; for(int i = 1;i < l;i ++){ Mp[i] = mx > i ? min(Mp[2*id-i],mx-i) : 1; while(s[i + Mp[i]] == s[i - Mp[i]]) Mp[i]++; if(i + Mp[i] > mx){ mx = i+Mp[i]; id = i; } } } int main() { while(scanf("%s",&line) != EOF){ //memset(Mp,0,sizeof(Mp)); int ans = 0; int le = strlen(line); Manacher(le); for(int i = 0;i < le*2+2;i ++) ans = max(ans,Mp[i] - 1); cout<<ans<<endl; } return 0; }