Subject to the effect:
There is known a rooted tree of n nodes. There are m interrogation. Each interrogation x and y are numbers given pair of nodes, asking grandchild relationship between x and y.
Problem-solving ideas:
sequence
sequence, the first record of the node access time
, complete access time
if
in
within the sub-tree, then there must be
#include<cstdio>
using namespace std;
struct Line {
int from, to, next;
}e[80010];
int n, m, cnt, root;
int st[40010], ed[40010], last[40010];
inline void add(int x, int y) {
e[++cnt] = (Line){x, y, last[x]}; last[x] = cnt;
}
void dfs(int now, int fa) {
++cnt;
st[now] = cnt;
for (int i = last[now]; i; i = e[i].next)
if (e[i].to != fa)
dfs(e[i].to, now);
ed[now] = cnt;
}
int main() {
scanf("%d", &n);
for (int x = 0, y = 0, i = 1; i <= n; ++i) {
scanf("%d %d", &x, &y);
if (y == -1) root = x;
else add(x, y), add(y, x);
}
cnt = 0;
dfs(root, -1);
scanf("%d", &m);
for (int x = 0, y = 0, i = 1; i <= m; ++i) {
scanf("%d %d", &x, &y);
if (st[x] < st[y] && ed[y] <= ed[x]) puts("1"); else
if (st[y] < st[x] && ed[x] <= ed[y]) puts("2"); else
puts("0");
}
}