最长回文
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 7868 Accepted Submission(s): 2691
Problem Description
给出一个只由小写英文字符a,b,c...y,z组成的字符串S,求S中最长回文串的长度.
回文就是正反读都是一样的字符串,如aba, abba等
回文就是正反读都是一样的字符串,如aba, abba等
Input
输入有多组case,不超过120组,每组输入为一行小写英文字符a,b,c...y,z组成的字符串S
两组case之间由空行隔开(该空行不用处理)
字符串长度len <= 110000
两组case之间由空行隔开(该空行不用处理)
字符串长度len <= 110000
Output
每一行一个整数x,对应一组case,表示该组case的字符串中所包含的最长回文长度.
Sample Input
aaaa abab
Sample Output
4 3manacher算法AC代码:#include <iostream> #include <cmath> #include <cstdlib> #include <cstring> #include <cstdio> #include <queue> #include <ctime> #include <algorithm> #define ll long long using namespace std; const int INF = 1e9; const int maxn = 110005; char str[2 * maxn], ss[maxn]; int p[maxn * 2]; void init(){ int i, l; str[0] = '@', str[1] = '#'; for(i = 0, l = 2; ss[i]; i++, l += 2) { str[l] = ss[i]; str[l + 1] = '#'; } str[l] = '\0'; } int solve(){ int ans = 0, mx = 0, id; for(int i = 0; str[i]; i++) { if(mx > i) p[i] = p[2 * id - i] > mx - i ? mx - i : p[2 * id - i]; else p[i] = 1; while(str[i + p[i]] == str[i - p[i]]) p[i]++; if(i + p[i] > mx) { mx = i + p[i]; id = i; } if(p[i] > ans) ans = p[i]; } return ans - 1; } int main() { while(~scanf("%s", ss)) { init(); printf("%d\n", solve()); } return 0; }