POJ 3974 - Palindrome(manacher)


分析:

manacher求最長迴文字串

代碼:

#include <iostream>

using namespace std;

const int maxn = 1000010;
char s[maxn], t[2 * maxn];
int p[2 * maxn];

void manacher()
{
    int id = 0, mx = 0;
    for (int i = 1; t[i] != '\0'; ++i) {
        p[i] = mx > i ? min(p[2 * id - i], mx - i) : 1;
        while (t[i + p[i]] == t[i - p[i]]) 
            p[i]++;
        if (i + p[i] > mx) {
            mx = i + p[i];
            id = i;
        }
    }
}

int main() 
{
    ios::sync_with_stdio(false);
    int _case = 1;
    while(cin >> s && s[0] != 'E') {
        int k = 0;
        t[k++] = '$';
        for (int i = 0; s[i] != '\0'; ++i) {
            t[k++] = '#';
            t[k++] = s[i];
        }
        t[k++] = '#';
        t[k] = '\0';
        manacher();
        int ans = 0;
        for (int i = 1; t[i] != '\0'; ++i) {
            ans = max(p[i], ans);
        }
        cout << "Case " << _case++ << ": " << ans - 1 << endl;
    }

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章