Hdu 5371 Manacher算法

Manacher算法:對於字符串str[ ], 找出所有以str[i]爲中心的迴文串的最長長度。

#include<stdio.h>
#include<algorithm>

using namespace std;

const int N = 100008;

int a[N];
int b[N<<1];
int p[N<<1];
int len;

void kp()
{
    int mx = 0, id = 0;
    for(int i = 0; i < len; i++)
    {
        if(mx > i)
            p[i] = min(p[(id<<1) - i], mx - i);
        else p[i] = 1;
        for(; i - p[i] >= 0 && b[i - p[i]] == b[i + p[i]]; p[i]++);
        if(p[i] + i > mx)
        {
            mx = p[i] + i;
            id = i;
        }
    }
}


int main ()
{
    int t;

    scanf("%d", &t);
    int k = 1;
    while(t--)
    {
        int n;
        scanf("%d", &n);
        len = 0;
        b[len++] = -1;
        for(int i = 0; i < n; i++){
            scanf("%d", &b[len++]);
            b[len++] = -1;
        }
        kp();
        int ans = 1;
        for(int i = 2; i < len-1; i += 2)
        {
            for(int j = ans; j <= p[i]; j+=2)
            {
                if(p[i+j-1] >= j)
                    ans = j;
            }
        }
        printf("Case #%d: %d\n", k++, ans/2*3);
    }

    return 0;

}
/*
10
10
3 2 2 3 3 2 15 6 7 0
*/


發佈了49 篇原創文章 · 獲贊 9 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章