• 算法笔记--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
  • 相关阅读:
    大数据下的质量体系建设
    快速打造属于你的接口自动化测试框架
    测试环境问题排查的那些事儿
    100个任务,用多机实现
    shell 在一个文件中查找数字
    shell中的awk使用
    shell怎么实现多进程
    删除字符串S1中的子串S2
    C++11的新特性
    C++里面普通指针怎么转换成智能指针
  • 原文地址:https://www.cnblogs.com/widsom/p/10450782.html
Copyright © 2020-2023  润新知