poj 3974 分类: poj templates 2015-07-05 22:24 18人阅读 评论(0) 收藏


Manacher算法, 用来解决 最长回文子串 一类问题,俗称马拉车算法,时间复杂度 O(n)


#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>

const int maxl = 1000005;
const char end[5] = "END";
#define clear(arr) memset(arr,0,sizeof(arr))

char ch[maxl], s[maxl<<1];
int sl, par[maxl<<1];

void init()
{
    int l = strlen(ch);

    clear(s), clear(par);

    for(int i = 0; i < l; i++)
        s[i<<1|1] = ch[i], s[i<<1] = 255;

    sl = l<<1|1, s[sl-1] = 255;
}
int solve()
{

    int ret = 0;
    for(int i = 1, id = 0, mx = 0; i < sl-1; i++)
    {
        par[i] = (i < mx)?(std::min(mx-i,par[id*2-i])):1;
#define Check(t) ((t)-par[t] >= 0 && (t)+par[t] < sl)       
        while(Check(i) && s[i-par[i]] == s[i+par[i]]) par[i]++;

        if(i + par[i] > mx) id = i, mx = i + par[i];

        ret = std::max(par[i] - 1, ret);
    }
    return ret;
}


int main()
{
    int T = 0;
#ifndef ONLINE_JUDGE
    freopen("poj3974.in","r",stdin);
    freopen("poj3974.out","w",stdout);
#endif

    while(scanf("%s",ch) != EOF)
    {
        if(!strcmp(ch, end)) break;

        printf("Case %d: ",++T);
        init(), printf("%d\n",solve());
    }

#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-07-05 22:24  <Dash>  阅读(113)  评论(0编辑  收藏  举报