我这怎么错了呀!!!
查看原帖
我这怎么错了呀!!!
395825
AThls123楼主2022/12/10 14:42

我炸了。 实在不知道错哪了!!

#include <iostream>
#include <cstring>

using namespace std;
const int N = 2e6+35;
char A[N]; int P[N], in[N];

inline int read(){
  char c; int sign = 1;
  while((c = getchar()) < '0' || c > '9') if(c == '-') sign = -1;
  int res = c - '0';
  while((c = getchar()) >= '0' && c <= '9') res = res * 10 + c - '0';
  return res * sign;
}

int head[N*2], ver[N*2], nxt[N*2], tot;
int dep[N], top[N], Size[N], son[N], fa[N];

inline void add(int x,int y){
  ver[++tot] = y; nxt[tot] = head[x]; head[x] = tot;
}

void kmp(){
  cin >> A+1;
  int len = strlen(A+1);
  for(int i = 1, j = 0; i < len; ++i){
    while(j && A[i+1] != A[j+1]) j = P[j];
    if(A[i+1]==A[j+1])++j;
    P[i+1]=j;
  }
  for(int i = 1; i <= len; ++i){
    add(i, P[i]); add(P[i], i);
  }
}

void dfs1(int x,int fx){
  fa[x] = fx; dep[x] = dep[fx] + 1; Size[x] = 1;
  for(int i = head[x]; i; i = nxt[i]){
    int y = ver[i];
    if(y == fx) continue;
    dfs1(y,x);
    Size[x] += Size[y];
    if(Size[son[x]] < Size[y]) son[x] = y;
  }
}

void dfs2(int x,int TOP){
  top[x] = TOP;
  if(!son[x]) return ;
  dfs2(son[x], TOP);
  for(int i = head[x]; i; i = nxt[i]){
    int y = ver[i];
    if(y == fa[x] || y == son[x]) continue;
    dfs2(y,y);
  }
}

int lca(int x,int y){
  while(top[x]!=top[y]){
    if(dep[top[x]] < dep[top[y]]) swap(x,y);
    x = fa[top[x]];
  }
  if(dep[x] > dep[y]) swap(x,y);
  return x;
}

int main(){
  kmp();
  dfs1(0,0); dfs2(0,0);
  int m = read();
  for(int i = 1; i <= m; ++i){
    int x = read(), y = read();
    int LCA = lca(x,y);
    if(LCA==x || LCA==y) printf("%d\n", fa[LCA]);
    else printf("%d\n", LCA);
  }
  return 0;
}

2022/12/10 14:42
加载中...