#include #include #include #include #include #include typedef long long ll; using namespace std; const int MAXN = 300000 + 100; vectorv[MAXN]; int n, m; int up[MAXN][25], tin[MAXN], tout[MAXN]; int tim; void dfs(int x, int anc) { tin[x] = tim; tim++; up[x][0] = anc; //cerr << x << " " << anc << "\n"; for (int i = 1; i < 23; i++) { up[x][i] = up[ up[x][i -1] ][i - 1]; //cerr << up[x][i] << "a\n"; } for (int i = 0; i < v[x].size(); i++) { int to = v[x][i]; if (to == anc) { continue; } //cerr << to << "\n"; dfs(to, x); } tout[x] = tim; tim++; } int isAnc(int x, int y) { return (tin[x] <= tin[y] && tout[y] <= tout[x]); } int lca(int x, int y) { if (x == y) { return x; } if (isAnc(x, y) ) { return x; } if (isAnc(y, x) ) { return y; } for (int i = 22; i >= 0; i--) { if (!isAnc(up[x][i], y) ) { x = up[x][i]; } } return up[x][0]; } struct Fenwick { static const int MAXM = 4*MAXN; int r[MAXM]; void modify(int x, int y) { for (; x < MAXM; x = (x|(x + 1) ) ) { r[x] += y; } } int sum(int x) { int res = 0; for (;x >= 0; x = ( (x & (x + 1) )- 1 )) { res += r[x]; } return res; } }; Fenwick on, under; int in[MAXN]; int brute(int a, int b, int c, int d) { set was; int lab = lca(a, b); was.insert(lab); while (a != lab) { was.insert(a); a = up[a][0]; } while (b != lab) { was.insert(b); b = up[b][0]; } int lcd = lca(c, d); if (was.find(lcd) != was.end() ) { return 1; } while (c != lcd) { if (was.find(c) != was.end() ) { return 1; } c = up[c][0]; } while (d != lcd) { if (was.find(d) != was.end() ) { return 1; } d = up[d][0]; } return 0; } int qA[MAXN], qB[MAXN]; int main() { scanf("%d", &n); //n = 49; for (int i = 2; i <= n; i++) { int aa, bb; scanf("%d%d", &aa, &bb); //aa = i; //bb = rand() % (i - 1) + 1; //cerr << aa << " " << bb << endl; v[aa].push_back(bb); v[bb].push_back(aa); } tin[0] = -1; tout[0] = (1<<25); dfs(1, 0); int q; scanf("%d", &q); //q = 1000; for (int it = 0; it < q; it++) { if (it % 10000 == 0) { cerr << it << endl; } int a, b; scanf("%d%d", &a, &b); //a = rand() % n + 1; //b = rand() % n + 1; //cerr << a << " " << b << endl; qA[it] = a; qB[it] = b; /*int l = lca(a, b); int res = on.sum(tin[a]) + on.sum(tin[b]) - 2*on.sum(tin[l]); res += under.sum(tout[l]) - under.sum(tin[l] - 1); res += in[l]; printf("%d\n", res);*/ int br = 0; for (int j = 0; j < it; j++) { br += brute(a, b, qA[j], qB[j]); } //cerr << br << endl; //assert(br == res);*/ printf("%d\n", br); /*on.modify(tin[l], 1); on.modify(tout[l], -1); under.modify(tin[a], 1); under.modify(tin[b], 1); under.modify(tin[l], -2); in[l]++;*/ } return 0; } /* 5 1 2 1 3 3 4 3 5 4 4 5 4 2 1 3 1 2 */