#include using namespace std; #define ALL(x) (x).begin(),(x).end() #define REP(i, n) for(ll i=0; i<(ll)(n); i++) #define PER(i, n) for(ll i=(ll)(n)-1; i>=0; i--) template int LB(const vector& v, T x) { return lower_bound(ALL(v),x)-v.begin(); } template int UQ(T& v) { sort(ALL(v)); v.erase(unique(ALL(v)),v.end()); return v.size(); } template bool chmax(T &a, T b) { return a bool chmin(T &a, T b) { return a>b ? a=b, true : false; } template using rpriority_queue = priority_queue,greater>; using ll=long long; const int INF=1e9+10; const ll INFL=4e18; using ld=long double; using lll=__int128_t; using ull=unsigned long long; using VI=vector; using VVI=vector; using VL=vector; using VVL=vector; using PL=pair; using VP=vector; using WG=vector>>; #ifdef LOCAL #include "./debug.hpp" #else #define debug(...) #define print_line #endif /// @brief LCA /// @ref verify: https://onlinejudge.u-aizu.ac.jp/status/users/Today03/submissions/1/GRL_5_C/judge/10572843/C++17 struct LCA { /// @brief コンストラクタ LCA(const vector>& g, int root=0) { int n=g.size(); int k=1; while((1<>(k,vector(n,-1)),dep=vector(n); dfs(g,root,-1); for(int i=0; i>i&1) u=par[i][u]; if(u==v) return u; for(int i=k-1; i>=0; i--) if(par[i][u]!=par[i][v]) u=par[i][u], v=par[i][v]; return par[0][u]; } /// @brief 頂点 u, v の距離を返す int distance(int u, int v) { return dep[u]+dep[v]-2*dep[lca(u,v)]; } /// @brief 頂点 x が u-v のパス上にあるか否かを返す bool is_on_path(int u, int v, int x) { return distance(u,x)+distance(x,v)==distance(u,v); } /// @brief 頂点 u から d 回遡った位置にある頂点を返す int climb(int u, int d) { int k=par.size(); for(int i=k-1; i>=0; i--) if(d>>i&1) u=par[i][u]; return u; } vector> par; vector dep; private: void dfs(const vector>& g, int now, int pre) { par[0][now]=pre; dep[now]=(pre==-1 ? 0 : dep[pre]+1); for(int nxt: g[now]) if(nxt!=pre) dfs(g,nxt,now); } }; //---------------------------------------------------------- const int B=320; void solve() { ll N; cin>>N; VVI G(N); REP(i,N-1) { ll u,v; cin>>u>>v; u--; v--; G[u].push_back(v); G[v].push_back(u); } LCA lca(G); ll Q; cin>>Q; vector> qry(Q); REP(i,Q) cin>>qry[i][0]>>qry[i][1], qry[i][1]--; unordered_set black; for(ll q=0; q*B(B,Q-q*B); unordered_set st, tmp; for(ll i=q*B; i que; for(ll x: black) if(!st.count(x)) { dist[x]=0; que.push(x); } while(!que.empty()) { int now=que.front(); que.pop(); for(int nxt: G[now]) { if(chmin(dist[nxt],dist[now]+1)) que.push(nxt); } } for(ll i=q*B; i>T; while(T--) solve(); }