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 91 92 93 94 95 96 97 98 99 100 101 102 103
| #include<algorithm> #include<iostream> #include<iomanip> #include<cstring> #include<cstdlib> #include<vector> #include<cstdio> #include<cmath> #include<queue> using namespace std; inline const int Get_Int() { int num=0,bj=1; char x=getchar(); while(x<'0'||x>'9') { if(x=='-')bj=-1; x=getchar(); } while(x>='0'&&x<='9') { num=num*10+x-'0'; x=getchar(); } return num*bj; } const int maxn=100005; int n,m,father[maxn],p[maxn][35],Depth[maxn],Size[maxn]; vector<int>edges[maxn]; void AddEdge(int x,int y) { edges[x].push_back(y); } void Dfs(int Now,int fa,int depth) { father[Now]=fa; Depth[Now]=depth; Size[Now]=1; for(int i=0; i<edges[Now].size(); i++) { int Next=edges[Now][i]; if(Next==fa)continue; Dfs(Next,Now,depth+1); Size[Now]+=Size[Next]; } } void Sparse_Table() { for(int i=1; i<=n; i++) for(int j=0; j<=log2(n); j++)p[i][j]=-1; for(int i=1; i<=n; i++)p[i][0]=father[i]; for(int j=1; j<=log2(n); j++) for(int i=1; i<=n; i++) if(p[i][j-1]!=-1)p[i][j]=p[p[i][j-1]][j-1]; } int LCA(int a,int b,int& _a,int& _b) { if(Depth[a]<Depth[b])swap(a,b); int k=log2(Depth[a]); for(int i=k; i>=0; i--) { if(Depth[a]==Depth[b])break; if(Depth[a]-(1<<i)>=Depth[b])a=p[a][i]; } if(a==b)return b; for(int i=k; i>=0; i--) if(p[a][i]!=-1&&p[a][i]!=p[b][i]) { a=p[a][i]; b=p[b][i]; } _a=a; _b=b; return p[a][0]; } int LCA(int x,int target) { int k=log2(Depth[x]); for(int i=k; i>=0; i--) if(Depth[x]-(1<<i)>target)x=p[x][i]; return x; } int main() { n=Get_Int(); for(int i=1; i<n; i++) { int x=Get_Int(),y=Get_Int(); AddEdge(x,y); AddEdge(y,x); } Dfs(1,-1,1); Sparse_Table(); m=Get_Int(); for(int i=1; i<=m; i++) { int x=Get_Int(),y=Get_Int(); if(x==y) { printf("%d\n",n); continue; } int _x,_y; int lca=LCA(x,y,_x,_y); if(Depth[x]==Depth[y])printf("%d\n",n-Size[_x]-Size[_y]); else { int dist1=Depth[lca]-Depth[x],dist2=Depth[lca]-Depth[y]; if((dist1+dist2)%2)puts("0"); else { if(Depth[x]<Depth[y])swap(x,y); int mid=Depth[x]+(dist1+dist2)/2; int target=LCA(x,mid); printf("%d\n",Size[father[target]]-Size[target]); } } } return 0; }
|