luogu P5829 【模板】失配树
传送门
首先,一个串的border定义为所有满足其前缀等于后缀的长度集合。
那怎么求border呢?会发现上面的定义就是kmp中的\(fail[|S|]\),而所有的border就是沿着这个fail指针一直跳下去,即\(fail[|S|],fail[fail[|S|]], \cdots\)
那么求两个前缀的最长公共border,就是从他们能跳到的所有长度中找公共最大的。如果我们从\(fail[i]\)向\(i\)连一条边,就形成了一棵树(失配树),而最长公共border就是他们两个的父亲的lca(不是本身,因为border不能包含自己)。
于是这道板子题就做出来了,感觉挺好理解的。
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<queue>
#include<assert.h>
#include<ctime>
using namespace std;
#define enter puts("")
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
#define forE(i, x, y) for(int i = head[x], y; ~i && (y = e[i].to); i = e[i].nxt)
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 1e6 + 5;
const int N = 20;
In ll read()
{
ll ans = 0;
char ch = getchar(), las = ' ';
while(!isdigit(ch)) las = ch, ch = getchar();
while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
if(las == '-') ans = -ans;
return ans;
}
In void write(ll x)
{
if(x < 0) x = -x, putchar('-');
if(x >= 10) write(x / 10);
putchar(x % 10 + '0');
}
int n, m;
char s[maxn];
int f[maxn], dep[maxn], fa[N + 2][maxn];
In void init()
{
f[1] = 0, dep[1] = 1;
for(int i = 2, j = 0; i <= n; ++i)
{
while(j && s[j + 1] != s[i]) j = f[j];
if(s[j + 1] == s[i]) ++j;
f[i] = j;
fa[0][i] = j, dep[i] = dep[j] + 1;
}
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= N; ++j) fa[j][i] = fa[j - 1][fa[j - 1][i]];
}
In int lca(int x, int y)
{
if(dep[x] < dep[y]) swap(x, y);
for(int i = N; i >= 0; --i) if(dep[fa[i][x]] >= dep[y]) x = fa[i][x];
if(x == y) return x;
for(int i = N; i >= 0; --i)
if(fa[i][x] ^ fa[i][y]) x = fa[i][x], y = fa[i][y];
return fa[0][x];
}
int main()
{
scanf("%s", s + 1);
n = strlen(s + 1);
init();
m = read();
for(int i = 1; i <= m; ++i)
{
int x = read(), y = read();
write(lca(fa[0][x], fa[0][y])), enter;
}
return 0;
}