Manacher算讲解:(讲得很好,花十几分钟看一下原理然后自己敲模板)
http://www.cnblogs.com/biyeymyhjob/archive/2012/10/04/2711527.html
看了上面的讲解,O(n)回文子串(Manacher)算法就大致了解了它的原理,这倒是个比较简单的知识点。
下面看模板题:
Description Andy the smart computer science student was attending an algorithms class when the professor asked the students a simple question, "Can you propose an efficient algorithm to find the length of the largest palindrome in a string?" Input Your program will be tested on at most 30 test cases, each test case is given as a string of at most 1000000 lowercase characters on a line by itself. The input is terminated by a line that starts with the string "END" (quotes for clarity). Output For each test case in the input print the test case number and the length of the largest palindrome. Sample Input abcbabcbabcba abacacbaaaab END Sample Output Case 1: 13 Case 2: 6 |
就是纯的求最长回文子串的题。
我自己写了一个模板:
#include<iostream> #include<cstring> #include<cstdlib> #include<cstdio> #include<set> #include<algorithm> using namespace std; char s[2000005]; int ans[2000005]; int change_str(char *s) { int len = strlen(s); s[len*2+2]=0; int j=len-1; for(int i=len*2+1; i>=1; i-=2) { s[i] = '#'; s[i-1] = s[j]; j--; } s[0] = '$'; return len*2+2; } int main() { int kase=1; while(scanf("%s",s)!=EOF&&s[0]!='E') { int len = change_str(s); int mx=0,id=0; ans[0]=1; for(int i=1; i<len; i++) { int r=i+ans[id-(i-id)] , l=i-ans[id-(i-id)]; if(r>mx) { r=max(mx+1,i+1); l=i-(r-i); while(s[l]==s[r]) { l--; r++; } mx = r-1; id = i; } ans[i] = r-i; } mx = 0; for(int i=0; i<len; i++) { mx = max(mx,ans[i]-1); } printf("Case %d: %d ",kase++,mx); } }