Manacher(馬拉車演算法)

lulaalu發表於2024-04-10

馬拉車

#include<iostream>
#include<string>
#include<fstream>
using namespace std;

#define endl "\n"
#define IOS ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
//#define cout fout
//#define cin fin
//ofstream fout("out_mlc.txt");
//ifstream fin("in.txt");


/*
馬拉車演算法思路
在每個字元間插入#標識
在遇到的每個字元向兩邊擴充套件
當無法擴充套件,把右邊的變為左邊的,
*/

int r[22000010] = { 0 };


void solve() {
    string str;
    cin >> str;
    //add
    string ns = "#";
    for (char ch : str) (ns += ch) += "#";
    
    int c = 0, ans = 0;
    for (int i = 1; i < ns.length(); i++) {
        if (c + r[c] > i)r[i] = min(r[2 * c - i], c + r[c] - i);
        while (i - r[i] >= 0 /* && i + r[i] < ns.length()*/ && ns[i - r[i]] == ns[i + r[i]])r[i]++;
        r[i]--;
        if (i + r[i] > c + r[c])c = i;//更新c位置
        ans = max(r[i], ans);
    }
    cout << ans;
}

int main() {
    IOS;
    
    solve();
    return 0;
}

相關文章