zoukankan      html  css  js  c++  java
  • 算法笔记--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
  • 相关阅读:
    实验一 GIT 代码版本管理
    实验五、单元测试
    实验四 代码审查
    结对编程 第二阶段
    结对编程第一阶段
    结对编程(一)
    实验1 GIT代码版本管理
    实验五 单元测试
    实验四 代码评审
    实验三 UML建模工具的安装与使用
  • 原文地址:https://www.cnblogs.com/widsom/p/10450782.html
Copyright © 2011-2022 走看看