hdu 4513 吉哥系列故事――完美队形II

manacher算法,在求p数组时多加个判断条件即可。

#include
#include
#include
using namespace std;
const int maxn = 1e5+10;
int h[maxn],H[maxn],p[maxn];
int n;
int init()
{
    H[0] = -1;
    H[1] = 0;
    int j = 2;
    for(int i = 0; i < n; i++)
    {
        H[j++] = h[i];
        H[j++] = 0;
    }
    H[j] = -3;
    return j;
}

int manacher()
{
    int len = init();
    int id = 0,mx = 0;
    int max_len = -1;
    for(int i = 1; i < len; i++)
    {
        p[i] = mx > i ? min(p[2*id-i],mx-i):1;
        while(H[i+p[i]] == H[i-p[i]] && (H[i-p[i]] == 0 || H[i-p[i]] <= H[i-p[i]+2]))//当H[i-p[i]]为插入字符或满足递增条件时,p[i]++
            p[i]++;
        if(i + p[i] > mx)
        {
            id = i;
            mx = i + p[i];
        }
        max_len = max(max_len,p[i]-1);
    }
    return max_len;
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        for(int i = 0; i < n; i++)
            scanf("%d",&h[i]);
        printf("%d\n",manacher());
    }
    return 0;
}

你可能感兴趣的:(manacher)