hihoCoder week1 最长回文子串

题目链接

https://hihocoder.com/contest/hiho1/problem/1

 

做法 Manacher

#include <bits/stdc++.h>
using namespace std;

#define Max(a,b) ((a>b)?a:b)
const int N = 1e6 + 10;
char s[N], c[N*2];

int dp[N*2]; // 以i为中心的 回文半径

void init(int len) 
{
    c[0]='$';
    for(int i=1;i<=len;i++){
        c[i*2-1]='#';
        c[i*2]=s[i];
    }
    c[2*len+1]='#';    
    c[2*len+2]='\0';
}

int manacher(int len)
{
    memset(dp, 0, sizeof(dp));
    int l = 2 * len + 1;
    int pos=0,R=0,mx=0;
    // printf(" ");
    for(int i=1; i<=l; i++) {
        if(i < R)
            dp[i]=min(dp[2*pos-i], R-i);
        else 
            dp[i]=1;
        while( 1<=i-dp[i] && i+dp[i]<=l && c[i-dp[i]] == c[i+dp[i]] )
            dp[i]++;
        if(i+dp[i] > R) {
            R = i + dp[i];
            pos = i;
        }
        mx = Max(mx, dp[i]-1);
        // printf("%d",dp[i]);
    } 
    //ans = mx;
    return mx;
}
int main()
{
    freopen("in.txt","r",stdin);
    int T; scanf("%d", &T);
    while(T--) {
        scanf(" %s", s+1);
        int len = strlen(s+1);
        init(len);
        // cout << c <<endl;
        cout << manacher(len) <<endl;
    }
    return 0;
}

 

posted @ 2018-11-06 14:49  Draymonder  阅读(138)  评论(0编辑  收藏  举报