1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| #include <iostream> #include <algorithm> #include <cstring> using namespace std;
const int N = 40007, M = 2*N;
int fa[N][17], depth[N], q[N]; int h[N], e[M], ne[M], idx;
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); depth[0] = 0; depth[root] = 1; int hh = 0, tt = 0; q[0] = root; while(hh <= tt) { int x = q[hh++]; for (int i = h[x]; i != -1; i = ne[i]) { int b = e[i]; if (depth[b] > depth[x] + 1) { depth[b] = depth[x] + 1; fa[b][0] = x; for (int i = 1; i <= 15; i++) { fa[b][i] = fa[fa[b][i-1]][i-1]; } q[++tt] = b; } } } }
int lca(int a, int b){ if (depth[a] < depth[b]) { swap(a, b); } for (int i = 15; i >= 0; i--) { if (depth[fa[a][i]] >= depth[b]) { a = fa[a][i]; } } if (a == b) return a; for (int i = 15; i >= 0; i--) { if (fa[a][i] != fa[b][i]) { a = fa[a][i]; b = fa[b][i]; } } return fa[a][0]; }
int main(){ memset(h, -1, sizeof h); int n,m; cin >> n; int root; for (int i = 0; i < n; i++) { int a, b; cin >> a >> b; if (b == -1) { root = a; } else { add(a,b); add(b,a); } } bfs(root); cin >> m; for (int i = 0; i < m; i++) { int x, y; cin >> x >> y; int ans = lca(x, y); if (ans == x) { cout << 1 << endl; } else if (ans == y) { cout << 2 << endl; } else { cout << 0 << endl; } } return 0; }
|