HDU3068 最长回文 Manacher's Algorithm 马拉车算法 模板

HDU3068

复习了一下这个算法,

注意数组大小要开两倍大。

 

#include <algorithm>
#include <iterator>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <iomanip>
#include <bitset>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <cmath>
#include <queue>
#include <list>
#include <map>
#include <set>
using namespace std;
//#pragma GCC optimize(3)
//#pragma comment(linker, "/STACK:102400000,102400000")  //c++
#define lson (l, mid, rt << 1)
#define rson (mid + 1, r, rt << 1 | 1)
#define debug(x) cerr << #x << " = " << x << "\n";
#define pb push_back
#define pq priority_queue

typedef long long ll;
typedef unsigned long long ull;

typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
typedef pair<int, pii> p3;

//priority_queue<int> q;//这是一个大根堆q
//priority_queue<int,vector<int>,greater<int> >q;//这是一个小根堆q
#define fi first
#define se second
//#define endl '\n'

#define OKC                      \
    ios::sync_with_stdio(false); \
    cin.tie(0)
#define FT(A, B, C) for (int A = B; A <= C; ++A) //用来压行
#define REP(i, j, k) for (int i = j; i < k; ++i)
//priority_queue<int ,vector<int>, greater<int> >que;

const ll mos = 0x7FFFFFFFLL;  //2147483647
const ll nmos = 0x80000000LL; //-2147483648
const int inf = 0x3f3f3f3f;
const ll inff = 0x3f3f3f3f3f3f3f3fLL; //18
const int mod = 998244353;

const double PI = acos(-1.0);

// #define _DEBUG;         //*//
#ifdef _DEBUG
freopen("input", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif
/*-----------------------showtime----------------------*/
int p[300009];
char str[300009], t[300009];
int Manacher(char *str, int len) {
    t[0] = '$';
    t[1] = '#';
    int tot = 2;
    for (int i = 0; i < len; i++) {
        t[tot++] = str[i];
        t[tot++] = '#';
    }

    int mx = 0, id = 0, reslen = 0, resCenter = 0;
    for (int i = 0; i < tot; i++) {
        if (i < mx)
            p[i] = min(p[2 * id - i], mx - i);
        else
            p[i] = 1;
        while (t[i + p[i]] == t[i - p[i]]) p[i]++;
        if (p[i] + i > mx) {
            mx = i + p[i];
            id = i;
        }
        if (reslen < p[i]) { reslen = p[i], resCenter = i; }
    }
    return reslen;
}
int main() {
    while (~scanf("%s", str)) {
        int len = strlen(str);
        printf("%d\n", Manacher(str, len) - 1);
    }
    return 0;
}

 

posted @ 2018-08-21 09:47  ckxkexing  阅读(257)  评论(0编辑  收藏  举报