写倍增写到怀疑人生
觉得没有任何问题但是交上去就是WA
最后发现“#ifndef ONLINE_JUDGE”在玲珑OJ上不能用
原串最长的后缀等于该串的前缀(?)这个东西可以用KMP的next数组求
next数组构成一棵树(每个点有且只有1个失配父亲,0没有失配父亲),答案相当于求next[a]和next[b]的LCA
倍增求即可
注意:区分深度和该点在原串中所代表的前缀的长度
#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#define LOG 25
#define N 200050
using namespace std;
vector<int> e[N];
int Jump[N][LOG+1],D[N],fa[N];
int nex[N],m,a,b;
int n;
char s[N];
void dfs(int u) {
D[u] = D[ fa[u] ] + 1;
for (int i=0;i<(int)e[u].size();i++) {
int v = e[u][i];
Jump[v][0] = u;
fa[v] = u;
dfs(v);
}
}
void pre() {
for (int i=1;i<=LOG;i++)
for (int j=0;j<=n;j++) Jump[j][i] = Jump[ Jump[j][i-1] ][ i-1 ];
}
int LCA(int u,int v) {
if (D[u] < D[v]) swap(u,v);
for (int i=LOG;i>=0;i--)
if (D[ Jump[u][i] ] >= D[v]) u = Jump[u][i];
if (u == v) return u;
for (int i=LOG;i>=0;i--)
if (Jump[u][i] != Jump[v][i])
u = Jump[u][i] , v = Jump[v][i];
return Jump[u][0];
}
void init() {
for (int i=0;i<=n;i++) e[i].clear();
for (int i=0;i<=n;i++)
for (int j=0;j<=LOG;j++) Jump[i][j] = 0;
for (int i=0;i<=n;i++) D[i] = nex[i] = fa[i]= 0;
}
void solve() {
init();
scanf("%s",s+1); n = strlen(s+1);
nex[1] = 0; int j = 0;
e[0].push_back(1);
for (int i=2;i<=n;i++) {
while (j && s[j+1] != s[i]) j = nex[j];
if (s[j+1] == s[i]) j++;
nex[i] = j;
e[j].push_back(i);
}
dfs(0); pre();
scanf("%d",&m);
while (m--) {
scanf("%d%d",&a,&b);
int f = LCA(a,b);
if (f == a || f == b) f = nex[f];
printf("%d\n",f);
}
}
int main() {
int T = 0; scanf("%d",&T);
for (int _=1;_<=T;_++) {
printf("Case #%d:\n",_);
solve();
}
return 0;
}