#include<bits/stdc++.h>
#define int long long
#define PB push_back
#define F first
#define S second
#define all(x) begin(x), end(x)
using namespace std;

typedef pair<int,int> pii;

const int MOD = 1e9 + 7;
const int maxn = 200007;

vector<int> G[maxn] = {};
vector<int> chart[maxn] = {};

int P[maxn][20] = {};
int dep[maxn] = {};
int in[maxn] = {};

int tick = 0;
void dfs(int x, int d) {
    in[x] = ++tick;
    chart[d].PB(x);
    dep[x] = d;
    for (auto y : G[x]) {
        dfs(y, d+1);
    }
}

int anc(int x, int k) {
    for (int i=19; i>=0; i--) {
        if (dep[P[x][i]] >= k) {
            x = P[x][i];
        }
    }

    return x;
}

int BS(int l, int r, int U,int D) {
    // printf("1(%lld, %lld)\n", l, r);
    if (l == r)
        return l;
    int m = (l + r) / 2;
    if (in[anc(chart[D][m], dep[U])] >= in[U])
        return BS(l, m, U, D);
    else
        return BS(m+1, r, U, D);
}

int BS2(int l, int r, int U,int D) {
    // printf("2(%lld, %lld)\n", l, r);
    if (l == r)
        return l;
    int m = (l + r) / 2;
    if (in[anc(chart[D][m], dep[U])] > in[U])
        return BS2(l, m, U, D);
    else
        return BS2(m+1, r, U, D);
}

int cmp1(int a, int b, int k) {
    return in[anc(a, k)] < in[anc(b, k)];
}

int32_t main() {
    int N,Q;

    cin >> N;
    for (int i=2; i<=N; i++) {
        cin >> P[i][0];
        G[P[i][0]].PB(i);
    }
    dep[0] = -1;
    dfs(1, 0);

    for (int i=1; i<20; i++) {
        for (int j=1; j<=N; j++) {
            P[j][i] = P[ P[j][i-1] ][i-1];
        }
    }

    // for (int i=1; i<=N; i++) {
    //     printf("%lld >>> ", i);
    //     for (int j=0; j<5; j++) {
    //         printf("%lld ", P[i][j]);
    //     }
    //     printf("\n");
    // }


    cin >> Q;
    while (Q--) {
        int U, D;
        cin >> U >> D;
        if (dep[U] > D) {
            printf("0\n");
            continue;
        } else if (dep[U] == D) {
            printf("1\n");
            continue;
        } else {
            int L = BS(0, chart[D].size(), U, D);
            int R = BS2(0, chart[D].size(), U, D);
            int ans = R - L;
            // printf("[%lld, %lld)\n", L, R);
            printf("%lld\n", ans);
        }
    }
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define DEBUG(x) cout << '>' << #x << ':' << x << endl;
#define REP(i,n) for(ll i=0;i<(n);i++)
#define FOR(i,a,b) for(ll i=(a);i<(b);i++)
#define FORC(i,a,b,c) for(ll i=(a);i<(b);i+=(c))
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
#define ff first
#define ss second
#define dd long double
#define all(x) x.begin(),x.end()

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    ll t;
    cin>>t;
    while(t--){
        ll lower,higher;
        cin>>lower>>higher;
        ll term=max(higher-2*lower+1,0ll);
        ll n=term;
        ll ans=n*(2+(n-1));
        ans/=2;
        cout<<ans<<endl;
    }
}
