ural 1297 最长回文串 manacher 算法

算法内容 http://blog.sina.com.cn/s/blog_70811e1a01014esn.html

 

题目直接看输出即可, 注意前后放 ? #, #*. 然后找最大回文串长度应该是 rid[i]*2 + (str[i] =='#')

#include<cstdio>

#include<cstring>

#include<cstdlib>

#include<algorithm>

#include<string>

using namespace std;



const int N = 1024;



char s[N];

int rid[N<<2];

string t;

void init(){

    int len = strlen(s);

    t += '?';

    for(int i = 0; i < len; i++){

        t += '#';

        t += s[i];

    }

    t += "#*";

}

void GetRid(){

    int i = 1;

    for(int i=1,j=0,k,End=(int)t.size(); i < End-1; ){

        while( t[i-j-1] == t[i+j+1] ) j++;

        rid[i] = j;

        for(k = 1; k<=j && rid[i-k]!=rid[i]-k; k++)

            rid[i+k] = min( rid[i-k], rid[i]-k );

        i += k;

        j = max( j-k, 0 );

    }

}

int main(){

    

    scanf("%s", s );

    init();    

    GetRid();

        

    int len = (int)t.size();

    int m = 0, pos = -1;

    for(int i = 1; i < len-1; i++){

        if( m < (rid[i]*2+(t[i]!='#')) ){

            m = (rid[i]*2+(t[i]!='#')), pos = i;    

        }    

    }

    string ans;

    for(int i = pos-rid[pos]; i < pos+rid[pos]; i++){

        if( t[i] != '#' ) ans += t[i];    

    }

    printf("%s\n", ans.c_str() );

//    for(int i = 0; i < len; i++){

//        printf("%c ", t[i]);    

//    }puts("");

//    for(int i = 0; i < len; i++)

//        printf("%d ", rid[i] );    

//    puts("");    

    return 0; }
View Code

 

你可能感兴趣的:(man)