算法竞赛进阶指南---0x14(Hash)Palindrome

题面

在这里插入图片描述

题解

  1. 题意就是让求一个字符串中最长的回文字串,可以用 Manacher 模板题 ,也可用字符串hash来做,这里主要讲字符串hash做法
  1. 对于一个回文串 以中点为分界线,两边的串是相同的,那么我们就可以用hash值来判断两边的串是否相同 ,例如 abcdcba ,我们可以正着算一遍hash,逆着算一遍hash,然后枚举每一个点,二分以这个点为分界点的长度,比较其hash是否相同
  1. 回文串分奇偶,对于奇数的有中点,对于偶数的没有,为了方便,我们可以使回文串都变为奇数,只需要在每个字母中间加一个未出现过的字符即可

代码1

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
typedef unsigned long long ULL;
const int N = 2e6 + 10;
const int P = 131;

char s[N];
ULL hl[N], hr[N], p[N];

ULL get(ULL h[], int l, int r) {
    
    
    return h[r] - h[l - 1] * p[r - l + 1];
}

int main() {
    
    

    int t = 0;
    while (cin >> s + 1, strcmp(s + 1, "END")) {
    
    
        int n = strlen(s + 1);
        n *= 2;
        for (int i = n; i > 0; i -= 2) {
    
    
            s[i] = s[i / 2];
            s[i - 1] = '#';
        }

        p[0] = 1;
        for (int i = 1, j = n; i <= n; i++, j--) {
    
    
            hl[i] = hl[i - 1] * P + s[i];
            hr[i] = hr[i - 1] * P + s[j];
            p[i] = p[i - 1] * P;
        }

        int res = 0;
        for (int i = 1; i <= n; i++) {
    
    
            int l = 0, r = min(i - 1, n - i);
            while (l < r) {
    
    
                int mid = (l + r + 1) >> 1;
                if (get(hl, i - mid, i - 1) != get(hr, n - (i + mid) + 1, n - (i + 1) + 1)) r = mid - 1;
                else l = mid;
            }
            if (s[i - l] == '#') res = max(res, l);
            else res = max(res, l + 1);
        }
        cout << "Case " << ++t << ": " << res << endl;
    }

    return 0;
}


代码2(Manacher)

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>

using namespace std;
const int N = 1e6 + 10;

char a[2 * N];
int p[2 * N];

int Manacher(string c) {
    
    
    int l = 0;
    a[l++] = '$', a[l++] = '#';
    for (int i = 0; i < c.size(); i++) {
    
    
        a[l++] = c[i];
        a[l++] = '#';
    }
    a[l] = '0';
    int mx = 0;
    int id = 0;
    int maxlen = -1;
    for (int i = 1; i < l - 1; i++) {
    
    
        p[i] = mx > i ? min(p[2 * id - i], mx - i) : 1;
        while (a[i - p[i]] == a[i + p[i]]) {
    
    
            p[i]++;
        }
        if (i + p[i] > mx) {
    
    
            mx = i + p[i];
            id = i;
        }
        if (p[i] > maxlen) {
    
    
            maxlen = p[i] - 1;
        }
    }
    return maxlen;
}

int main() {
    
    

    string s;
    int t = 0;
    while (cin >> s && s != "END") {
    
    
        cout << "Case " << ++t << ": " << Manacher(s) << endl;
    }

    return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_44791484/article/details/113854151