• 算法笔记--manacher算法


    参考:https://www.cnblogs.com/grandyang/p/4475985.html#undefined

    模板:

    const int N = 1e5 + 10;
    int p[N];
    string manacher(string s) {
        string t = "$#";
        for (int i = 0; i < s.size(); ++i) {
            t += s[i];
            t += '#';
        }
        int mx = 0, id = 0, resl = 0, resc = 0;
        for (int i = 1; i < t.size(); ++i) {
            p[i] = mx > i ? min(p[2*id-i], mx-i) : 1;
            while(i+p[i] < t.size() && i-p[i] >= 0 && t[i+p[i]] == t[i-p[i]]) ++p[i];
            if(mx < i+p[i]) mx = i+p[i], id = i;
            if(resl < p[i]) resl = p[i], resc = i;
        }
        return s.substr((resc - resl)/2, resl-1);
    }

     HDU 3068

    代码:

    #pragma GCC optimize(2)
    #pragma GCC optimize(3)
    #pragma GCC optimize(4)
    #include<bits/stdc++.h>
    using namespace std;
    #define y1 y11
    #define fi first
    #define se second
    #define pi acos(-1.0)
    #define LL long long
    //#define mp make_pair
    #define pb push_back
    #define ls rt<<1, l, m
    #define rs rt<<1|1, m+1, r
    #define ULL unsigned LL
    #define pll pair<LL, LL>
    #define pli pair<LL, int>
    #define pii pair<int, int>
    #define piii pair<pii, int>
    #define pdd pair<double, double>
    #define mem(a, b) memset(a, b, sizeof(a))
    #define debug(x) cerr << #x << " = " << x << "
    ";
    #define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    //head
    
    const int N = 3e5 + 10;
    int p[N];
    int manacher(string s) {
        string t = "$#";
        for (int i = 0; i < s.size(); ++i) {
            t += s[i];
            t += '#';
        }
        int mx = 0, id = 0, resl = 0, resc = 0;
        for (int i = 1; i < t.size(); ++i) {
            p[i] = mx > i ? min(p[2*id-i], mx-i) : 1;
            while(t[i+p[i]] == t[i-p[i]]) ++p[i];
            if(mx < i+p[i]) mx = i+p[i], id = i;
            if(resl < p[i]) resl = p[i], resc = i;
        }
        return resl-1;
    }
    int main() {
        string s;
        while(cin >> s) {
            cout << manacher(s) << endl;
        }
        return 0;
    }
    View Code
  • 相关阅读:
    python
    shader example
    shader 关键字
    Android Studio如何导出可供Unity使用的aar插件详解 转
    adb
    知识
    Unity实现模拟按键
    小知识
    图种制作命令
    八卦
  • 原文地址:https://www.cnblogs.com/widsom/p/10450782.html
Copyright © 2020-2023  润新知