#include <bits/stdc++.h>

using namespace std;

const int MAXN = 150000 + 5;

vector<vector<int>> adj;

int n, m;
int lift[20][MAXN];
int depth[MAXN];

void dfs(int u, int p)
{
    lift[0][u] = p;
    // cerr << u << '\n';
    for(int v : adj[u])
    {
        if(v == p)
            continue;
        depth[v] = depth[u] + 1;
        dfs(v, u);
    }
}

int get_anc(int u, int d)
{
    for(int j = 0; j < 20 ;j++)
    {
        if((d >> j) & 1)
        {
            u = lift[j][u];
        }
    }
    return u;
}

int get_lca(int u, int v)
{
    if(depth[u] < depth[v])
        swap(u, v);
    u = get_anc(u, depth[u] - depth[v]);
    if(u == v)
        return u;
    for(int i = 19; i >= 0; i--)
    {
        if(lift[i][u] != lift[i][v])
        {
            u = lift[i][u];
            v = lift[i][v];
        }
    }
    return lift[0][u];
}

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() + 1;
    m = S.size();
    adj.clear();
    adj.resize(n);
    for(auto [u, v] : R)
    {
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
    dfs(0, -1);
    for(int i = 1; i < 20; i++)
    {
        for(int j = 0; j < n; j++)
        {
            lift[i][j] = lift[i - 1][lift[i - 1][j]];
        }
    }
    vector<int> ans;
    for(int i = 0; i < m; i++)
    {
        // cerr << "D" << S[i] << ' ' << T[i] << '\n';
        int w = get_lca(S[i], T[i]);
        // cerr << S[i] << ' ' << T[i] << ' ' << w << '\n';
        int dist = depth[S[i]] + depth[T[i]] - 2 * depth[w] + 1;
        if(I[i])
            ans.push_back(dist);
        else
            ans.push_back(0);
    }
    return ans;
}