HDU 3068 最長迴文 Manacher演算法,

來源:互聯網
上載者:User

HDU 3068 最長迴文 Manacher演算法,

Manacher演算法是個解決Palindrome問題的O(n)演算法,可以說是個超級演算法了,秒殺其他一切Palindrome解決方案,包括複雜的尾碼數組。


網上很多解釋,最好的解析文章當然是Leetcode的了:http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html


這裡總結一下思想重點:


1 原字串的字元間插入新的字元, 如#,方便統一所有的字元中心,比如aa和aba的字元中心不一樣的,aa的字元中心可以說是aa,而aba的中心則是b,而插入#之後,aa成#a#a#,其中心是一個字元#,而aba插入#a#b#a#,中心還是一個字元b。


2 充分利用前面已經計算出的資訊來計算後面的資訊,這裡主要利用palindrome的對稱性的特性,那麼就可以利用對稱中心前半段的資訊計算後半段的資訊了。這個是最佳化演算法到O(n)的關鍵。 因為對稱中心是不斷右移的,故此在對稱中心內的求解只需直接copy前半段的資訊就可以,而超出當前對稱範圍的就需要expand Palindrome了。


3 防止溢出,前面加一個額外的特殊字元,如'~',和前面的插入字元不一樣。後面也需要插入字元,但是為什麼很多程式不插入字元呢?那是因為C++的char都是以'\0'結束的,故此,不插入也是可以的,下面程式明顯插入'\0'到結尾了。


4 需要維護最右點資訊,中心資訊和P數組,P數組的含義是以i點為中心的最長palindrome子字串的長度,這裡是長度+1,方便計算。


關鍵代碼就幾行,但是思想卻是十分難的。


#include <stdio.h>#include <string.h>const int MAX_2L = 220010;char txt[MAX_2L];int P[MAX_2L];int len;inline int min(int a, int b) { return a < b? a : b; }inline int max(int a, int b) { return a > b? a : b; }void preProcess(){len = strlen(txt);int i = len-1, j = (len<<1);txt[j+2] = '\0';txt[j+1] = '#';for ( ; i >= 0; i--){txt[j--] = txt[i];txt[j--] = '#';}txt[0] = '~';}int main(){while (gets(txt)){preProcess();len = len << 1 | 1;int maxLen = 0, right = 0, center = 0;for (int i = 1; i <= len; i++){P[i] = i<right ? min(P[(center<<1)-i], right-i) : 1;while (txt[i-P[i]] == txt[i+P[i]]) P[i]++;maxLen = max(maxLen, P[i]);if (right < i+P[i]) center = i, right = i+P[i];}printf("%d\n", maxLen-1);gets(txt); //get rid of empty line}return 0;}






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.