最近の公祖先-------孫

nnを含むツリーを考える

各ノードのルート付き無向ツリー、ノード番号は互いに異なりますが、必ずしも1〜n1〜nではありません

クエリ、各クエリはノード番号xxのペアを提供します

そして、yy

、xxに質問

yy

祖父母関係。入力フォーマット入力の最初の行には、ノードの数を示す整数が含まれ、次のnn

行ごとに1組の整数aa

そしてBB

、意味aa

そしてBB

間に無向エッジがあります。bbの場合

はい−1−1

、それからaa

木の根です; n + 2n + 2

行は整数mmです

問い合わせ数を示し、次のmm

行、行ごとに2つの異なる正の整数xx

そして、yy

、問い合わせを示します。各クエリの出力形式(xxの場合)

はい、yy

祖先出力11

yyの場合

はいxx

祖先の出力22

、それ以外の場合は00を出力

データ範囲1≤n、m≤4×1041≤n、m≤4×104


1≤各ノードの数≤4×1041≤各ノードの数≤4×104

サンプル入力:10
234 -1
12 234
13 234
14 234
15 234
16 234
17 234
18 234
19 234
233 19
5
234 233
233 12
233 13
233 15
233 19
サンプル出力:1
0
0
0
2

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 40010, M = N * 2;
int n, m;
int h[N], e[M], ne[M], idx;
int depth[N], fa[N][16];
int q[N];
void add(int a, int b) {
 e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void bfs(int root) {
 memset(depth, 0x3f, sizeof depth);
 int hh = 0, tt = 0;
 depth[0] = 0, depth[root] = 1;
 q[0] = root;
 while (hh <= tt) {
  int t = q[hh++];
  for (int i = h[t]; ~i; i = ne[i]) {
   int j = e[i];
   if (depth[j] > depth[t] + 1) {
    depth[j] = depth[t] + 1;
    q[++tt] = j;
    fa[j][0] = t;
    for (int k = 1; k <= 15; k++)
     fa[j][k] = fa[fa[j][k - 1]][k - 1];
   }
  }
 }
}
int lca(int a, int b) {
 if (depth[a] < depth[b])   swap(a, b);
 for (int k = 15; k >= 0; k--)
  if (depth[fa[a][k]] >= depth[b])
   a = fa[a][k];
 if (a == b)    return a;
 for (int k = 15; k >= 0; k--)
  if (fa[a][k] != fa[b][k]) {
   a = fa[a][k];
   b = fa[b][k];
  }
 return fa[a][0];
}
int main() {
 scanf("%d", &n);
 int root = 0;
 memset(h, -1, sizeof h);
 for (int i = 0; i < n; i++) {
  int a, b;
  scanf("%d%d", &a, &b);
  if (b == -1)    root = a;
  else           add(a, b), add(b, a);
 }
 bfs(root);
   scanf("%d", &m);
 while (m--) {
  int a, b;
  scanf("%d%d", &a, &b);
  int p = lca(a, b);
  if (p == a)   puts("1");
  else     if (p == b)    puts("2");
  else     puts("0");
 }
 return 0;
}
164のオリジナル記事が公開されました いいね112 訪問者6762

おすすめ

転載: blog.csdn.net/qq_45772483/article/details/105547795