思路
首先看到回文应该想到 Manacher 或 PAM。不过我并不是很会 Manacher,所以只能用 PAM 了。
题意是要求一对左端点相同的、长度为 的回文串。而 PAM 正好能维护以某个位置结尾的所有回文串,简直太契合了。
从后往前扫描,建出 PAM。记录每个节点最后一次被访问的位置(也就是最靠前的访问位置)。
我们知道 PAM 的失配树上,每个点的祖先就是它的回文后缀(此处倒着扫的,所以变成前缀)。所以问题转化为:找到一对祖孙节点,它们对应的长度分别为 ,且孙子的子树中。最后访问位置的最小值最小。
注意到询问是随机的,所以每一个长度 期望出现 次。那不妨把每一个深度为 的点扫一遍,看它的祖先中,是否有长度为 的节点即可。
期望时间复杂度 。
代码
代码是离线处理,实际上在线也没有问题的。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
char s[maxn];
int Q[maxn], ans[maxn];
vector<int> qs[maxn];
namespace pam{
int tr[maxn][26], fail[maxn], len[maxn], tot = 1, now = 1, loc[maxn];
char t[maxn];
int m = 0;
void init(){
len[1] = -1;
fail[0] = fail[1] = 1;
}
int getfail(int x){
while(t[m] != t[m - len[x] - 1]) x = fail[x];
return x;
}
void insert(char c, int id){
t[++ m] = c;
int x = getfail(now);
if(!tr[x][c - 'a']){
tot ++, len[tot] = len[x] + 2;
fail[tot] = tr[getfail(fail[x])][c - 'a'];
tr[x][c - 'a'] = tot;
}
now = tr[x][c - 'a'];
if(!loc[now]) loc[now] = id;
loc[now] = min(loc[now], id);
}
int head[maxn], nxt[maxn << 1], to[maxn << 1], cnt = 0;
void match(int u, int v){
nxt[++ cnt] = head[u], to[cnt] = v, head[u] = cnt;
}
void build(){
for(int i = 0; i <= tot; i ++){
if(i == 1) continue;
match(fail[i], i);
}
}
int tag[maxn], mn[maxn];
void dfs(int x, int f){
// printf("\t%d %d\n", x, f);
if(len[x] >= 0) tag[len[x]] ++;
mn[x] = loc[x];
for(int i = head[x]; i; i = nxt[i]){
int j = to[i];
if(j == f) continue;
dfs(j, x);
mn[x] = min(mn[x], mn[j]);
}
if(len[x] >= 0){
for(int i = 0; i < qs[len[x]].size(); i ++){
int j = qs[len[x]][i];
if(tag[Q[j]]) ans[j] = min(ans[j], mn[x]);
}
tag[len[x]] --;
}
}}
int main(){
int n, q;
scanf("%d %d %s", &n, &q, s + 1);
pam::init();
for(int i = n; i >= 1; i --) pam::insert(s[i], i);
for(int i = 1; i <= q; i ++){
int l1, l2;
scanf("%d %d", &l1, &l2);
Q[i] = l1, qs[l2].push_back(i);
ans[i] = 1e9;
}
pam::build(), pam::dfs(1, -1);
for(int i = 1; i <= q; i ++){
if(ans[i] == 1e9) printf("-1\n");
else printf("%d\n", ans[i]);
}
return 0;
}