CF208E.Blood Cousins

普及/提高-

通过率:0%

AC君温馨提醒

该题目为【codeforces】题库的题目,您提交的代码将被提交至codeforces进行远程评测,并由ACGO抓取测评结果后进行展示。由于远程测评的测评机由其他平台提供,我们无法保证该服务的稳定性,若提交后无反应,请等待一段时间后再进行重试。

题目描述

Polycarpus got hold of a family relationship tree. The tree describes family relationships of nn people, numbered 1 through nn . Each person in the tree has no more than one parent.

Let's call person aa a 1-ancestor of person bb , if aa is the parent of bb .

Let's call person aa a kk -ancestor (k>1) of person bb , if person bb has a 1-ancestor, and aa is a (k1)(k-1) -ancestor of bb 's 1-ancestor.

Family relationships don't form cycles in the found tree. In other words, there is no person who is his own ancestor, directly or indirectly (that is, who is an xx -ancestor for himself, for some xx , x>0 ).

Let's call two people xx and yy (xy)(x≠y) pp -th cousins (p>0) , if there is person zz , who is a pp -ancestor of xx and a pp -ancestor of yy .

Polycarpus wonders how many counsins and what kinds of them everybody has. He took a piece of paper and wrote mm pairs of integers viv_{i} , pip_{i} . Help him to calculate the number of pip_{i} -th cousins that person viv_{i} has, for each pair viv_{i} , pip_{i} .

输入格式

The first input line contains a single integer nn (1<=n<=105)(1<=n<=10^{5}) — the number of people in the tree. The next line contains nn space-separated integers r1,r2,...,rnr_{1},r_{2},...,r_{n} , where rir_{i} (1<=ri<=n)(1<=r_{i}<=n) is the number of person ii 's parent or 0, if person ii has no parent. It is guaranteed that family relationships don't form cycles.

The third line contains a single number mm (1<=m<=105)(1<=m<=10^{5}) — the number of family relationship queries Polycarus has. Next mm lines contain pairs of space-separated integers. The ii -th line contains numbers viv_{i} , pip_{i} (1<=vi,pi<=n)(1<=v_{i},p_{i}<=n) .

输出格式

Print mm space-separated integers — the answers to Polycarpus' queries. Print the answers to the queries in the order, in which the queries occur in the input.

输入输出样例

  • 输入#1

    6
    0 1 1 0 4 4
    7
    1 1
    1 2
    2 1
    2 2
    4 1
    5 1
    6 1
    

    输出#1

    0 0 1 0 0 1 1 
    
首页