2020NYIST个人积分赛第七场-H manacher+思維

86 阅读1分钟
原题链接:传送门

題目大意:给你一个字符串s,s1、s2分别是s的前缀字符串和后缀字符串(都可为空字符串),字符串t=s1+s2;求最长的回文串t并输出。


题目思路:先找到s两边对应的最大长度,然后在中间找边界的最长回文串。例如:abacsjsba。我们先找到左边的ab和右边的ba,剩下acsjs,再找该字符串包含边界的最大回文串,显然是sjs,最后ab+sjs+ba就是答案。


比赛最后块结束的时候交了一发,wa了,然后赛后debug很久也没出,最后发现manacher板子打错了。。太菜了。

AC代码:

//https://blog.csdn.net/hesorchen
#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <cmath>
#include <stack>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define endl '\n'
#define PI cos(-1)
#define ll long long
#define INF 0x3f3f3f3f
#define mod 1000000009
#define lowbit(abcd) (abcd & (-abcd))

char before[1000010];
char after[2000010];
int R[2000010];
int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        scanf("%s", before);
        int len = strlen(before);
        int s = -1;
        for (int i = 0; i < len; i++)
            if (before[i] != before[len - i - 1])
            {
                s = i - 1;
                break;
            }
        after[0] = '$';
        after[1] = '#';
        int ct = 2;
        for (int i = s + 1; i < len - s - 1; i++)
        {
            after[ct++] = before[i];
            after[ct++] = '#';
        }
        after[ct] = '@';
        int pos = 0;
        int maxx = 0;
        for (int i = 1; i < ct; i++)
        {
            if (i < maxx)
                R[i] = min(maxx - i, R[2 * pos - i]);
            else
                R[i] = 1;
            while (after[i + R[i]] == after[i - R[i]])
                R[i]++;
            if (R[i] + i > maxx)
            {
                maxx = R[i] + i;
                pos = i;
            }
        }
        int maxxx = -1;
        int l, r;
        l = r = -1;
        // cout << after << endl;
        for (int i = 1; i < ct; i++)
        {
            // cout << i << ' ' << R[i] << ' ' << ct << ' ' << endl;
            if (R[i] >= maxxx && (i - R[i] == 0 || i + R[i] - 1 == ct - 1))
            {
                l = i - R[i] + 1;
                r = i + R[i] - 1;
                maxxx = R[i];
            }
        }

        for (int i = 0; i <= s; i++)
            printf("%c", before[i]);
        // cout << endl;
        for (int i = l; i <= r; i++)
            if (after[i] == '#')
                continue;
            else
                printf("%c", after[i]);
        // cout << endl;
        for (int i = len - s - 1; i <= len - 1; i++)
            printf("%c", before[i]);
        cout << endl;
    }

    return 0;
}