Topic Link: Click to open the link
Test instructions
A tree given n points.
The following n-1 row gives the tree
Q a question.
Ask each question (u,v) How many points to the U-point distance from the tree = to V-point distance
Ideas:
First, the distance between the two points must be even, if the odd answer is 0.
Then use LCA to find the middle node.
Trick:u==v ans = n
#include "Cstdio" #include "iostream" #include "queue" #include "algorithm" #include "set" #include "queue" #include "Cmath "#include" string.h "#include" vector "using namespace std;template <class t>inline BOOL Rd (T &ret) {char c; int Sgn if (c = GetChar (), c = = EOF) return 0; while (c! = '-'-' && (c< ' 0 ' | | c> ' 9 ')) C = GetChar (); SGN = (c = = '-')? -1:1; ret = (c = = '-')? 0: (C-' 0 '); while (c = GetChar (), C >= ' 0 ' &&c <= ' 9 ') ret = ret * + (C-' 0 '); RET *= SGN; return 1;} Template <class t>inline void pt (T x) {if (x <0) {Putchar ('-'); x =-X; } if (X>9) pt (X/10); Putchar (x 10 + ' 0 ');} #define N 100500struct edge{int from, to, NEX;} Edge[2 * N];int Head[n], Edgenum, fa[n][20], dep[n], siz[n]; FA[I][X] is the first 2^x father of I (if the range is the root) void add (int u, int v) {Edge E = {u, V, Head[u]}; Edge[edgenum] = E; Head[u] = edgenum++;} void BFs (int root) {queue<int> q; Fa[root][0] = root; Dep[root] = 0; Siz[root] = 0; Q.push (root); while (!q.empty ()) {int u = q.front (); Q.pop (); for (int i = 1; i<20; i++) fa[u][i] = fa[fa[u][i-1]][i-1]; for (int i = head[u]; ~i; i = edge[i].nex) {int v = edge[i].to; if (v = = fa[u][0]) continue; DEP[V] = Dep[u] + 1; Fa[v][0] = u; Q.push (v); }}}void dfs (int u, int f) {siz[u] = 1; for (int i = head[u]; ~i; i = edge[i].nex) {int v = edge[i].to; if (v = = f) Continue; DFS (v, u); Siz[u] + = Siz[v]; }}int Lca (int x, int y) {if (Dep[x]<dep[y]) swap (x, y); for (int i = 0; i<20; i++) if ((Dep[x]-dep[y]) & (1 << i) x = Fa[x][i]; if (x = = y) return x; for (int i = n; I >= 0; i--) if (fa[x][i]! = Fa[y][i]) x = fa[x][i], y = fa[y][i]; return fa[x][0];} void Init () {memset (head,-1, sizeof head); edgenum = 0;} int n, m;int go (int D, int x) {while (d) {int z = log10 (1.0*d)/log10 (2.0); x = Fa[x][z]; D-= 1 << z; } return x;} int main () {rd (n); Init (); for (int i = 1, u, v; i < n; i++) {rd (U); Rd (v); Add (U, v); Add (V, u); } BFS (1); DFS (1, 1); RD (M); int x, y; while (m--) {rd (x); Rd (y); if (x = = y) {pt (n); Putchar (' \ n '); continue;} if (Dep[x]>dep[y]) swap (x, y); int L = LCA (x, y); int len = dep[x]-dep[l] + dep[y]-dep[l]; if (len & 1) {Putchar (' 0 '); } else {len = LEN/2-1; int a = Go (len, y), B = fa[a][0]; if (b = = L) {pt (N-siz[a]-Siz[go (len, X)]); } else PT (Siz[b]-siz[a]); } putchar (' \ n '); } return 0;}
Codeforces 519E A and B and lecture Rooms LCA