HDU 3068 最長迴文(Manacher演算法解決最長迴文串問題)

畫船聽雨發表於2016-09-29

這算是個歷史遺留問題了啊,當時沒怎麼看,最近又發現了,標記一下。腦子越來越不好使了啊。

Manacher演算法:http://blog.csdn.net/xingyeyongheng/article/details/9310555

解釋一下:p[id]+id表示最遠(從左向右)可以到達的字串。

最長迴文

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 18167    Accepted Submission(s): 6677


Problem Description
給出一個只由小寫英文字元a,b,c...y,z組成的字串S,求S中最長迴文串的長度.
迴文就是正反讀都是一樣的字串,如aba, abba等
 

Input
輸入有多組case,不超過120組,每組輸入為一行小寫英文字元a,b,c...y,z組成的字串S
兩組case之間由空行隔開(該空行不用處理)
字串長度len <= 110000
 

Output
每一行一個整數x,對應一組case,表示該組case的字串中所包含的最長迴文長度.
 

Sample Input
aaaa abab
 

Sample Output
4 3
 

Source
 
#include <algorithm>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <iomanip>
#include <stdio.h>
#include <string>
#include <queue>
#include <cmath>
#include <stack>
#include <ctime>
#include <map>
#include <set>
#define eps 1e-9
///#define M 1000100
///#define LL __int64
#define LL long long
///#define INF 0x7ffffff
#define INF 0x3f3f3f3f
#define PI 3.1415926535898
#define zero(x) ((fabs(x)<eps)?0:x)
#define mod 1000000007

#define Read() freopen("autocomplete.in","r",stdin)
#define Write() freopen("autocomplete.out","w",stdout)
#define Cin() ios::sync_with_stdio(false)

using namespace std;

const int maxn = 222000;
char str[maxn];
char s[maxn];
int p[maxn];
int main()
{
    while(~scanf("%s", s))
    {
        int len = strlen(s);
        str[0] = '#';
        str[1] = '$';
        for(int i = 0, j = 2; i < len; i++)
        {
            str[j++] = s[i];
            str[j++] = '$';
        }
        int id = 0;
        int Max = 0;
        memset(p, 0, sizeof(p));
        for(int i = 2; i < 2*len+1; i++)
        {
            if(p[id]+id > i)
                p[i] = min(p[2*id-i], p[id]+id-i);
            else
                p[i] = 1;
            while(str[i-p[i]] == str[i+p[i]]) p[i]++;
            if(p[id]+id < i+p[i]) id = i;
            Max = max(Max, p[i]);
        }
        cout<<Max-1<<endl;
    }
    return 0;
}


相關文章