【模板】失配树 学习笔记

· · 算法·理论

前言

依稀记得一年前,是 ttx 大战模拟赛,并发表重要结论:原来在 nxt 数组上建树,就是失配树!

当时的我也是个刚学失配树的菜鸡,现在因为一些题重新复习,却发现竟然如此简单,5 分钟之内就写完代码,甚至没有调试直接通过,这让我不禁感慨:前面忘了,中间忘了,后面也忘了,总之就是总之了。

Problem

求两个前缀的最长公共 border。

Solution

直接倍增维护 nxt 数组,查询的时候,根据倍增 LCA 的套路,先把两个跳到同一层,再从较大的次数往较小的次数枚举,看能不能跳,然后就做完了。

我甚至认为这个不能算作是模板,不就是一个简单的倍增和 KMP 的应用吗?

Code

#include <bits/stdc++.h>
#define rep(i,l,r) for(int i=l;i<=r;i++)
#define int long long
#define dd double
using namespace std;
template <typename T> inline void D(T &x)
{
    x=0;bool f=0;char ch=getchar();
    while('0'>ch||ch>'9'){if(ch=='-')f=!f;ch=getchar();}
    while('0'<= ch&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
    x=f?-x:x;return;
}
template <typename T> inline void P(T x)
{
    if(x<0)putchar('-'),x=-x;
    if(x>9)P(x/10);
    putchar(x%10+'0');return;
}
const int N = 1e6 + 10;
int n, m;
char s[N];
int nxt[N][25];
int dep[N];
void solve()
{
    cin >> s + 1;
    n = strlen(s + 1);
    for (int i = 2, p = 0; i <= n; i ++)
    {
        while (p && s[p + 1] != s[i]) p = nxt[p][0];
        nxt[i][0] = p = p + (s[p + 1] == s[i]);
    }
    dep[0] = 1;
    for (int i = 1; i <= n; i ++)
    {
        dep[i] = dep[nxt[i][0]] + 1;
    }
    for (int j = 1; j <= 22; j ++)
    {
        for (int i = 1; i <= n; i ++) nxt[i][j] = nxt[nxt[i][j - 1]][j - 1];
    }
    cin >> m;
    for (int i = 1; i <= m; i ++)
    {
        int x, y;
        cin >> x >> y;
        if (dep[x] != dep[y])
        {
            if (dep[x] < dep[y]) swap(x, y);
            for (int j = 22; j >= 0; j --)
            {
                if (dep[nxt[x][j]] >= dep[y]) x = nxt[x][j];
            }
        }
        for (int j = 22; j >= 0; j --)
        {
            if (nxt[x][j] != nxt[y][j]) x = nxt[x][j], y = nxt[y][j];
        }
        cout << nxt[x][0] << '\n';
    }
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    //freopen(".in","r",stdin);freopen(".out","w",stdout);
    int T;T=1;
    while(T--)solve();
    return 0;
}