#include "infection.h"
#include <bits/stdc++.h>
using namespace std;

const int N = 2e5 + 5;
vector<int> g[N];
int up[N][20], lvl[N];

void dfs(int u, int p = 1) {
    up[u][0] = p;
    lvl[u] = lvl[p] + 1;
    for (int i = 1; i < 20; i++) {
        up[u][i] = up[up[u][i - 1]][i - 1];
    }
    for (int v : g[u]) {
        if (v == p) {
            continue;
        }
        dfs(v, u);
    }
}

int lca(int u, int v) {
    if (lvl[u] < lvl[v]) {
        swap(u, v);
    }
    for (int i = 19; i >= 0; i--) {
        if (lvl[up[u][i]] >= lvl[v]) {
            u = up[u][i];
        }
    }
    if (u == v) {
        return u;
    }
    for (int i = 19; i >= 0; i--) {
        if (up[u][i] != up[v][i]) {
            u = up[u][i];
            v = up[v][i];
        }
    }
    return up[u][0];
}

int dis(int u, int v) {
    return lvl[u] + lvl[v] - 2 * lvl[lca(u, v)];
}

vector<int> solve(vector<pair<int, int>> R, vector<long long> D, vector<int> S, vector<int> T, vector<bool> I) {
    int n = R.size() + 1;
    for (auto [u, v] : R) {
        u++, v++;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    int m = D.size();
    vector<int> ans(m);
    dfs(1);
    for (int i = 0; i < m; i++) {
        if (I[i]) {
            ans[i] = dis(S[i] + 1, T[i] + 1) + 1;
        } else {
            ans[i] = 0;
        }
    }
    return ans;
}
