#include "infection.h"
#include<bits/stdc++.h>
#define f first
#define s second
#define ll long long
using namespace std;
const ll maxn =1e6+10;
vector<ll> starts[maxn];
vector<ll> endss[maxn];
ll n,q;
ll bord[maxn];
vector<ll> edges[maxn];
ll depth[maxn];
ll st[25][maxn];
ll tin[maxn],tout[maxn];
ll timer=0;
void dfs(ll start,ll parent)
{
    tin[start]=++timer;
    st[0][start]=parent;
    for(auto e:edges[start])
    {
        if(e==parent) continue;
        depth[e]=depth[start]+1;
        dfs(e,start);
    }
    tout[start]=++timer;
}
void compLCA()
{
    for(ll j=1;j<25;j++)
    {
        for(ll i=1;i<=n;i++)
        {
            st[j][i]=st[j-1][st[j-1][i]];
        }
    }
}
bool isanc(ll u,ll v)
{
    if(tin[u]<=tin[v] && tout[u]>=tout[v]) return true;
    return false;
}
ll lca(ll u,ll v)
{
  //  prllf("in lca %d %d\n",u,v);
    if(isanc(u,v)) return u;
    if(isanc(v,u)) return v;
    if(depth[u]>depth[v]) swap(u,v);
    for(ll i=24;i>=0;i--)
    {
       // prllf("current v is %d\n",v);
        if(!isanc(st[i][v],u)) v=st[i][v];
    }
 //   prllf("out lca\n");
    return st[0][v];
}
std::vector<int> solve(
    std::vector<std::pair<int, int>> R,///rebra
    std::vector<long long> D,///nachalni dni
    std::vector<int> S,///nachalna poziciq
    std::vector<int> T,///krajna poziciq
    std::vector<bool> I///bolen/nebolen
)
{

    q=D.size();
    vector<int> mom;
    mom.clear();
    mom.assign(q,0);
    n=R.size()+1;
    for(ll i=0;i<q;i++) mom[i]=-1;
    for(ll i=0;i<n-1;i++)
    {
        R[i].f++;
        R[i].s++;
        edges[R[i].f].push_back(R[i].s);
        edges[R[i].s].push_back(R[i].f);
    }
    for(ll i=0;i<q;i++)
    {
        S[i]++;
        T[i]++;
    }
    dfs(1,1);
   // prllf("3\n");
    compLCA();
   // prllf("2\n");
    for(ll i=0;i<q;i++)
    {
       // prllf()
        mom[i]=depth[S[i]]+depth[T[i]]-2*depth[lca(S[i],T[i])]+1;
        if(!I[i]) mom[i]=0;
    }
    return mom;
}

