Palindrome
Time Limit: 15000MS | Memory Limit: 65536K | |
Total Submissions: 6562 | Accepted: 2416 |
Description
A string is said to be a palindrome if it reads the same both forwards and backwards, for example "madam" is a palindrome while "acm" is not.
The students recognized that this is a classical problem but couldn't come up with a solution better than iterating over all substrings and checking whether they are palindrome or not, obviously this algorithm is not efficient at all, after a while Andy raised his hand and said "Okay, I've a better algorithm" and before he starts to explain his idea he stopped for a moment and then said "Well, I've an even better algorithm!".
If you think you know Andy's final solution then prove it! Given a string of at most 1000000 characters find and print the length of the largest palindrome inside this string.
Input
Output
Sample Input
abcbabcbabcba abacacbaaaab END
Sample Output
Case 1: 13 Case 2: 6
求字符串中的最长回文子串。
直接使用Manacher算法,轻松求解。。
/************************************************************************* > File Name: Palindrome.cpp > Author: ZhangHaoRan > Mail: chilumanxi@gmail.com > Created Time: 2016年03月05日 星期六 10时04分20秒 ************************************************************************/ #include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<string> #include<vector> #include<set> #include<map> #include<queue> #include<list> #include<algorithm> using namespace std; const int MAXN = 1000000 + 10; char Ma[MAXN * 2]; int Mp[MAXN * 2]; char s[MAXN]; int len; int cas; void Manacher(){ int l = 0; Ma[l ++] = '$'; Ma[l ++] = '#'; for(int i = 0; i < len; i ++){ Ma[l ++] = s[i]; Ma[l ++] = '#'; } Ma[l] = 0; int ans = 0; int mx = 0, id = 0; for(int i = 0; i < l; i ++){ Mp[i] = mx > i ? min(Mp[2 * id - i], mx - i) : 1; while(Ma[i + Mp[i]] == Ma[i - Mp[i]]) Mp[i] ++; if(i + Mp[i] > mx){ mx = i + Mp[i]; id = i; } ans = max(ans , Mp[i] - 1); } printf("Case %d: %d\n", cas, ans); } int main(void){ cas = 0; while(1){ cas ++; scanf("%s", s); if(!strcmp(s, "END")) break; len = strlen(s); Manacher(); } return 0; }