#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
const ll N = 2e5;
vector <vector <ll> > gr;
vector <vector <ll> > bin_up(N, vector <ll> (20));
vector <ll> dist(N);
ll n, m;
void dfs(ll v, ll ls, ll d){
    dist[v] = d;
    bin_up[v][0] = ls;
    for (int i = 1; i < 20; i++){
        if((1<<i) <= dist[v])
            bin_up[v][i] = bin_up[bin_up[v][i-1]][i-1];
    }
    for (auto u : gr[v]){
        if(u == ls) continue;
        dfs(u, v, d + 1);
    }
}
ll go(ll v, ll r){
    for (int i = 19; i > -1; i--){
        if(r >= (1<<i)){
            r -= (1<<i);
            v = bin_up[v][i];
        }
    }
    return v;
}
ll lca(ll a, ll b){
    if(dist[a] < dist[b])
        swap(a, b);
    a = go(a, dist[a] - dist[b]);
    if(a == b) return a;
    for (int i = 19; i > -1; i--){
        if(bin_up[a][i] != bin_up[b][i])
        {
            a = bin_up[a][i];
            b = bin_up[b][i];
        }
    }
    return bin_up[a][0];
}
std::vector<int> solve(std::vector<std::pair<int, int>> R, std::vector<long long> D, std::vector<int> S, std::vector<int> T, std::vector<bool> I){
    n = R.size();
    m = D.size();
    gr.resize(n+1);
    for (int i = 0; i < n; i++){
        ll a = R[i].first;
        ll b = R[i].second;
        gr[a].push_back(b);
        gr[b].push_back(a);
    }
    dfs(1, -1, 0);
    vector <int> rec;
    for (int i = 0; i < m; i++){
        ll a = S[i];
        ll b = T[i];
        ll ans = dist[S[i]] + dist[T[i]];
        ll L = lca(a, b);
        ans -= 2 * dist[L];
        if(I[i] == 1)
        rec.push_back(ans + 1);
        else rec.push_back(0);
    }
    return rec;
}