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;
}

猜你喜欢

转载自blog.csdn.net/li1615882553/article/details/84869868