#include using namespace std; const int N = 40010, M = 80010; int e[M], h[N], idx, ne[M]; void add(int a, int b) { e[idx] = b, ne[idx] = h[a], h[a] = idx++; } // 暴力法可以过掉 6/10 int n; int depth[N]; int fa[N]; void bfs(int root) { queue q; q.push(root); depth[root] = 1; fa[root] = -1; while (q.size()) { int u = q.front(); q.pop(); for (int i = h[u]; ~i; i = ne[i]) { int v = e[i]; if (!depth[v]) { depth[v] = depth[u] + 1; fa[v] = u; q.push(v); } } } } int lca(int a, int b) { if (depth[a] < depth[b]) swap(a, b); while (depth[a] < depth[b]) b = fa[b]; while (a != b) a = fa[a], b = fa[b]; return a; } int main() { #ifndef ONLINE_JUDGE freopen("1172.in", "r", stdin); #endif memset(h, -1, sizeof h); scanf("%d", &n); int a, b, m, root; for (int i = 0; i < n; i++) { scanf("%d %d", &a, &b); if (b == -1) root = a; else add(a, b), add(b, a); } bfs(root); scanf("%d", &m); while (m--) { 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; }