#include <bits/stdc++.h>

#define ll long long
#define inf 0x3f3f3f3f
#define pii pair<int, int>
#define int long long
using namespace std;
const int maxn = 3e5+10;

template <typename _tp>
inline void read(_tp& x) {
    char ch = getchar(), sgn = 0;
    while (ch ^ '-' && !isdigit(ch)) ch = getchar();
    if (ch == '-') ch = getchar(), sgn = 1;
    for (x = 0; isdigit(ch); ch = getchar()) x = x * 10 + ch - '0';
    if (sgn) x = -x;
}
vector<int>e[maxn];
int L[maxn], R[maxn], tim;
vector<int>v[maxn];
int d[maxn], d1[maxn];
void dfs(int u, int dep){
    L[u] = ++tim;
    d[tim] = dep;
    d1[u] = dep;
    v[dep].push_back(L[u]);
    for(auto v: e[u]){
        dfs(v, dep+1);
    }
    R[u] = tim;
}

bool isson(int u, int v){
    return(L[u] >= L[v] && L[u] <= R[v]);
}
signed main(){
    int n;
    scanf("%lld", &n);
    for(int i = 2; i <= n; ++i){
        int a;
        scanf("%lld", &a);
        e[a].push_back(i);
    }    
    dfs(1, 0);
    int q;
    scanf("%lld", &q);
    while(q--){
        int a, b;
        scanf("%lld%lld", &a, &b);
        if(d1[a] > b){
            printf("0\n");
            continue;
        }
        else if(d1[a] == b){
            printf("1\n");
            continue;
        }
        cout << upper_bound(v[b].begin(), v[b].end(), R[a]) - lower_bound(v[b].begin(), v[b].end(), L[a]) << endl;
        //printf("%lld\n", ans);
    }
    //return 0;
}
/*
7
1 1 2 2 4 2
4
1 2
7 2
4 1
5 5
*/
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<bitset>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<deque>
#include<list>
#include<iomanip>
#include<cmath>
#include<cstring>
#include<functional>
#include<cstdio>
#include<cstdlib>
#include<numeric>

using namespace std;

#define repr(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rep(i, n) repr(i, 0, n)
#define INF 2e9
#define MOD 1000000007
//#define MOD 998244353
#define LINF (long long)4e18
#define jck 3.141592
#define PI acos(-1.0)

const double EPS = 1e-10;

using ll = long long;
using Pi = pair<int,int>;
using Pl = pair<ll,ll>;


int main(){
    int T; cin >> T;
    while(T--) {
        string s; cin >> s;
        int n = s.size();
        string t = "atcoder";
        if(s > t){
            cout << 0 << endl;
            continue;
        }
        bool ok = false;
        rep(i,n) {
            if(s[i] != 'a') ok = true;
        }
        if(!ok){
            cout << -1 << endl;
            continue;
        }
        int ans = INF;
        repr(i,1,n){
            if(s[i] > 't') {
                ans = min(ans,i-1);
            }
            else if(s[i] != 'a') {
                ans = min(ans,i);
            }
        }
        cout << ans << endl;
    }
}

