1. 程式人生 > >Manacher_1040 Longest Symmetric String (25 分)

Manacher_1040 Longest Symmetric String (25 分)

1040 Longest Symmetric String (25 分)

Given a string, you are supposed to output the length of the longest symmetric sub-string. For example, given Is PAT&TAP symmetric?, the longest symmetric sub-string is s PAT&TAP s, hence you must output 11.

Input Specification:

Each input file contains one test case which gives a non-empty string of length no more than 1000.

Output Specification:

For each test case, simply print the maximum length in a line.

Sample Input:

Is PAT&TAP symmetric?

Sample Output:

11

直接是Manacher演算法的模板題,參見:Manacher演算法詳解及模板 

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <set>
#define INF 0x3f3f3f3f
#define ll long long

using namespace std;
const int maxn = 1005;
string s;
int p[maxn*2];

int main()
{
    getline(cin,s);
    int len = s.length();
    for(int i = len;i >= 0;i --)
    {
        s[i+i+2] = s[i];
        s[i+i+1] = '#';
    }
    s[0] = '*';
    int maxlen = 0,id = 0;
    for(int i = 2;i < len*2+1;i ++) id-i+id
    {
        if(p[id]+id > i) p[i] = min(p[id*2-i],p[id]+id-i);   //當此節點被前面的迴文串包含
        else p[i] = 1;
        while(s[i+p[i]] == s[i - p[i]]) p[i]++;
        if(p[id] + id < p[i] + i) id = i;                   //迴文串可以到達最右端的點
        if(maxlen < p[i]) maxlen = p[i];
    }
    printf("%d\n",maxlen-1);
    return 0;
}