#include "infection.h"
#include "bits/stdc++.h"

#define pii pair<int, int>
#define pb push_back
#define ar array
#define ll long long

const ll inf = 1e18 + 7;

using namespace std;

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;

    vector<vector<int>> pon(n);

    for (auto [u, v]: R) {
        pon[u].pb(v);
        pon[v].pb(u);
    }

    int m = D.size();

    int tt = 0;

    vector<int> d(n), tin(n), tout(n);

    vector<ar<int, 20>> anc(n);

    function<void(int, int)> dfs = [&](int u, int p) {
        d[u] = d[p] + 1;

        tin[u] = ++tt;

        anc[u][0] = p;

        for (int i = 1; i < 20; i++) {
            anc[u][i] = anc[anc[u][i - 1]][i - 1];
        }

        for (auto v: pon[u]) {
            if (v != p) {
                dfs(v, u);
            }
        }

        tout[u] = ++tt;
    };

    dfs(0, 0);

    auto isanc = [&](int u, int v) {
        return (tin[u] <= tin[v] && tout[v] <= tout[u]);
    };

    auto getlca = [&](int u, int v) {
        if (isanc(u, v)) {
            return u;
        }

        if (isanc(v, u)) {
            return v;
        }

        for (int i = 19; i >= 0; i--) {
            if (!isanc(anc[u][i], v)) {
                u = anc[u][i];
            }
        }

        return anc[u][0];
    };

    auto dist = [&](int u, int v) {
        int lca = getlca(u, v);

        return d[u] - d[lca] + d[v] - d[lca] + 1;
    };

    vector<int> ret;

    for (int i = 0; i < m; i++) {
        ret.pb(I[i] ? dist(S[i], T[i]) : 0);
    }

    return ret;
}

/*signed main() {
    int n, m;

    std::cin >> n;
    std::cin >> m;

    std::vector<std::pair<int, int>> edges = {};
    std::vector<long long> day;
    std::vector<int> start;
    std::vector<int> target;
    std::vector<bool> infected;

    for (int i = 0; i < n - 1; i++) {
        int u, v;
        std::cin >> u >> v;
        edges.emplace_back(u, v);
    }

    for (int i = 0; i < m; i++) {
        long long _d, _s, _t, _i;
        std::cin >> _d >> _s >> _t >> _i;
        day.push_back(_d);
        start.push_back(_s);
        target.push_back(_t);
        infected.push_back(_i);
    }

    const auto ans = solve(edges, day, start, target, infected);
    for (const auto it : ans) {
        std::cout << it << std::endl;
    }

    return 0;
}*/


