马拉车反演

· · 题解

题目分析

  1. 题目就是已知回文子串长度,出现回文串,就去想对应位置相等,发现随着各个回文子串堆叠,有些位置的字符一定相同,把不同位置分成若干类,这种思想一眼就是并查集

  2. 发现用并查集维护字符一定相等的集关系后,不同集的字符可能相同,也可能不同,需要根据是否符合回文长度限制贪心地选择字符。

那么如何判断是否会破坏回文长度限制? 3.建立一个链表,记录哪些位置对一定不能是相同字符。 4.实现过程(优化):对于并查集合并操作,分析发现存在同一集合内的反复合并,用马拉车算法“扩展未扫描区域,已有已扫描区域”的方法维护

#include <algorithm>
#include <cstring>
#include <cstdio>
#define LL long long
#define Re register int
using namespace std;
const int N = 1e5 + 3;
int n, m, x, o, A[N << 1], f[N << 1], co[N], fa[N], head[N], judge[30];
struct QAQ
{
    int to, next;
} a[N << 2]; // 注意链表要开4N
inline void add(Re x, Re y) { a[++o].to = y, a[o].next = head[x], head[x] = o; }
inline void in(Re &x)
{
    int f = 0;
    x = 0;
    char c = getchar();
    while (c < '0' || c > '9')
        f |= c == '-', c = getchar();
    while (c >= '0' && c <= '9')
        x = (x << 1) + (x << 3) + (c ^ 48), c = getchar();
    x = f ? -x : x;
}
inline int find(Re x) { return x == fa[x] ? x : fa[x] = find(fa[x]); }
inline void merge(Re x, Re y)
{
    if ((x = find(x)) != (y = find(y)))
        fa[x] = y;
}
int main()
{
    //  freopen("123.txt","r",stdin);
    in(n), m = n << 1 | 1;
    for (Re i = 1; i <= n; ++i)
        fa[i] = i;
    for (Re i = 1; i <= n; ++i)
        in(x), A[i << 1] = x;
    for (Re i = 1; i < n; ++i)
        in(x), A[i << 1 | 1] = x;
    for (Re i = 2, mid = 0, r = 0; i < m; ++i)
    {
        f[i] = (i <= r ? min(f[(mid << 1) - i], r - i + 1) : 1);
        while (f[i] - 1 < A[i])
        { // f[i]-1才是以i为中心的实际最长回文串长度
            ++f[i];
            if (!(i - f[i] + 1 & 1))//“新的扩展”且不是辅助点,进行合并
                merge(i - f[i] + 1 >> 1, i + f[i] - 1 >> 1); // 对于奇点(辅助点)就不要merge了
        }
        add(i - f[i] >> 1, i + f[i] >> 1), add(i + f[i] >> 1, i - f[i] >> 1); // 这里必定是偶点,可以直接除2进行连边
        if (i + f[i] - 1 > r)
            mid = i, r = i + f[i] - 1;
    }
    //    for(Re i=2;i<=m;i+=2)printf("%d ",f[i]-1);puts("");
    for (Re i = 1; i <= n; ++i)
        if (!co[find(i)])
        {
            memset(judge, 0, sizeof(judge));
            for (Re j = head[i]; j; j = a[j].next)
                judge[co[find(a[j].to)]] = 1; // i对立点的颜色都不能选
            for (Re j = 1; j <= 26 && !co[find(i)]; ++j)
                if (!judge[j])
                    co[find(i)] = j;
        }
    for (Re i = 1; i <= n; ++i)
        printf("%c", 'a' + co[find(i)] - 1);
}