Polycarpus got hold of a family tree. The found tree describes the family relations of *n* people, numbered from 1 to *n*. Every person in this tree has at most one direct ancestor. Also, each person in the tree has a name, the names are not necessarily unique.

We call the man with a number *a* a 1-ancestor of the man with a number *b*, if the man with a number *a* is a direct ancestor of the man with a number *b*.

We call the man with a number *a* a *k*-ancestor (*k* &gt; 1) of the man with a number *b*, if the man with a number *b* has a 1-ancestor, and the man with a number *a* is a (*k* - 1)-ancestor of the 1-ancestor of the man with a number *b*.

In the tree the family ties do not form cycles. In other words there isn't a person who is his own direct or indirect ancestor (that is, who is an *x*-ancestor of himself, for some *x*, *x* &gt; 0).

We call a man with a number *a* the *k*-son of the man with a number *b*, if the man with a number *b* is a *k*-ancestor of the man with a number *a*.

Polycarpus is very much interested in how many sons and which sons each person has. He took a piece of paper and wrote *m* pairs of numbers *v*<sub class="lower-index">*i*</sub>, *k*<sub class="lower-index">*i*</sub>. Help him to learn for each pair *v*<sub class="lower-index">*i*</sub>, *k*<sub class="lower-index">*i*</sub> the number of distinct names among all names of the *k*<sub class="lower-index">*i*</sub>-sons of the man with number *v*<sub class="lower-index">*i*</sub>.
The first line of the input contains a single integer *n* (1 ≤ *n* ≤ 10<sup class="upper-index">5</sup>) — the number of people in the tree. Next *n* lines contain the description of people in the tree. The *i*-th line contains space-separated string *s*<sub class="lower-index">*i*</sub> and integer *r*<sub class="lower-index">*i*</sub> (0 ≤ *r*<sub class="lower-index">*i*</sub> ≤ *n*), where *s*<sub class="lower-index">*i*</sub> is the name of the man with a number *i*, and *r*<sub class="lower-index">*i*</sub> is either the number of the direct ancestor of the man with a number *i* or 0, if the man with a number *i* has no direct ancestor. 

The next line contains a single integer *m* (1 ≤ *m* ≤ 10<sup class="upper-index">5</sup>) — the number of Polycarpus's records. Next *m* lines contain space-separated pairs of integers. The *i*-th line contains integers *v*<sub class="lower-index">*i*</sub>, *k*<sub class="lower-index">*i*</sub> (1 ≤ *v*<sub class="lower-index">*i*</sub>, *k*<sub class="lower-index">*i*</sub> ≤ *n*).

It is guaranteed that the family relationships do not form cycles. The names of all people are non-empty strings, consisting of no more than 20 lowercase English letters.
import os,sys,random,threading
from random import randint
from copy import deepcopy
from io import BytesIO, IOBase
from types import GeneratorType
from functools import lru_cache, reduce
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque
from itertools import accumulate, combinations, permutations
from heapq import  heapify, heappop, heappush
from typing import Generic, Iterable, Iterator, TypeVar, Union, List
from string import ascii_lowercase, ascii_uppercase
from math import ceil, floor, sqrt, pi, factorial, gcd, log, log10, log2, inf
from decimal import Decimal, getcontext
BUFSIZE = 4096
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin = IOWrapper(sys.stdin)
sys.stdout = IOWrapper(sys.stdout)
mod = int(1e9 + 7) #998244353
inf = int(1e20)
input = lambda: sys.stdin.readline().rstrip("\r\n")
MI = lambda :map(int,input().split())
li = lambda :list(MI())
ii = lambda :int(input())
py = lambda :print("YES")
pn = lambda :print("NO")
DIRS = [(0, 1), (1, 0), (0, -1), (-1, 0)]  # 右下左上
DIRS8 = [(0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0),(-1, 1)]  # →↘↓↙←↖↑↗


class BIT1:
    """单点修改,区间和查询"""

    __slots__ = "size", "bit", "tree"

    def __init__(self, n: int):
        self.size = n
        self.bit = n.bit_length()
        self.tree = [0]*(n+1)

    def add(self, index: int, delta: int) -> None:
        # index 必须大于0
        while index <= self.size:
            self.tree[index]+=delta
            index += index & -index

    def _query(self, index: int) -> int: 
        res = 0
        while index > 0:
            res += self.tree[index]
            index -= index & -index
        return res

    def query(self, left: int, right: int) -> int:
        return self._query(right) - self._query(left - 1)



n=ii()


g=[[] for _ in range(n+5)]


name=[None]*(n+5)

for i in range(1,n+1):
    s,fa=input().split()
    name[i]=s
    fa=int(fa)
    g[fa].append(i)
        
dep_node=[[] for _ in range(n+5)]

stack = [(0, 0)]
tmp = []

st = [None]*(n+5)  #节点找dfn
ed = [None]*(n+5)
st[0] = 0
dep = [0]*(n+5)    #深度
rank=[0]*(n+5)     #dfn找节点
while stack:
    u, s = stack.pop()
    if s:
        ed[u] = len(tmp) - 1
    else:
        st[u] = len(tmp)
        dep_node[dep[u]].append(st[u])
        rank[st[u]]=u
        tmp.append(u)
        stack.append((u, 1))
        for v in g[u]:
            if st[v] is None:
                stack.append((v, 0))
                dep[v]=dep[u]+1

query=[[] for _ in range(n+5)]

q=ii()

res=[0]*q

for i in range(q):
    v,k=li()
    if dep[v]+k<n+5:
        query[dep[v]+k].append([i,v])


for d in range(n+5):
    if len(dep_node[d])==0:
        continue
    arr=[]
    for i,v in query[d]:
        j=bisect_left(dep_node[d],st[v])
        if j>=len(dep_node[d]) or dep_node[d][j]>ed[v]:
            continue
        j2=bisect_left(dep_node[d],ed[v])
        if j2>=len(dep_node[d]) or dep_node[d][j2]>ed[v]:
            j2-=1
        arr.append([j,j2,i])
    bit=BIT1(len(dep_node[d])+5)
    arr.sort(key=lambda x:-x[1])
    idx={}
    for i in range(len(dep_node[d])):
        if len(arr)==0:
            break
        node=rank[dep_node[d][i]]
        s=name[node]
        if s in idx:
            bit.add(idx[s]+1,-1)
        idx[s]=i
        bit.add(i+1,1)
        while arr and arr[-1][1]<=i:
            L,R,pos=arr.pop()
            res[pos]=bit.query(L+1,R+1)
        
for i in res:
    print(i)