manacher algorithm (template)

effect

Calculating the longest palindrome string at each position of the string can also be said to calculate all palindrome intervals.

principle

I feel the algorithm is very similar to extending kmp to find the extend array.

Insert '$' in the first position to avoid discussion less than 0, and then insert '#' between each character, in order to avoid discussion on the parity length of the interval.

Use len [i] to represent the length of the right half of the longest palindrome at position i. Due to the above processing, the length of the right half of the interval here is the total length of the palindrome interval of the original string.

Let p represent the rightmost boundary reached during the calculation. a represents the position corresponding to p. The position where i is symmetric to a is 2 * a-i. If i + len [2 * a-i] does not exceed the range of p then len [i] = len [2 * a-i]. Otherwise, extend and update p and a.

void mana() {
    ios::sync_with_stdio(false);
    s.clear();
    ans.clear();
    s.push_back('$');
    s.push_back('#');
    for(int i = 0; ss[i]; i++) {
        s.push_back(ss[i]);
        s.push_back('#');
    }

    int a = 1, p = 1;
    for(int i = 1; i < s.size(); i++) {
        if(i < p && len[2 * a - i] < p - i) len[i] = len[2 * a - i];
        else {
            int l = p - i;
            while(i + l < s.size() && s[i + l] == s[i - l]) l++;
            len[i] = l;
            a = i;
            p = i + l;
        }
    }
}

Guess you like

Origin www.cnblogs.com/limil/p/12695075.html
Recommended