PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#SRD0000098. Quan hệ giữa các vùng (Regions)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Quan hệ giữa các vùng (Regions)

Regions

Source: IOI

Version: Phuoc Hung OJ Extended

Problem Statement

An organization has NN employees numbered from 11 to NN. Employee 11 is the chair. Each employee k≥2k\ge2 has exactly one direct supervisor Sk<kS_k<k, so the supervision relations form a tree rooted at employee 11.

Employee kk comes from region Hk∈{1,…,R}H_k\in\{1,\ldots,R\}. Employee xx is a manager of employee yy precisely when xx is a proper ancestor of yy in the supervision tree: moving from yy to supervisors reaches xx after at least one step. An employee is not a manager of themself.

For each query with two different regions (r1,r2)(r_1,r_2), count ordered pairs (x,y)(x,y) such that:

  • Hx=r1H_x=r_1;
  • Hy=r2H_y=r_2;
  • xx is a manager of yy.

Distinct pairs are counted separately, even if they share a manager or a subordinate.

Input

The first line contains N,R,QN,R,Q. The next NN lines describe employees in order: the first contains only H1H_1; the line for employee k=2,…,Nk=2,\ldots,N contains Sk,HkS_k,H_k. Finally, QQ lines contain two different region IDs r1,r2r_1,r_2.

Output

For every query, print one integer on its own line: the number of qualifying ordered pairs.

Subtasks

  • Subtask 1 (15 points): N≤2000N\le2000, R≤500R\le500, Q≤2000Q\le2000; each region has at most 500500 employees.
  • Subtask 2 (15 points): N≤50000N\le50000, R≤500R\le500, Q≤50000Q\le50000.
  • Subtask 3 (40 points): N≤100000N\le100000, Q≤100000Q\le100000; each region has at most 500500 employees.
  • Subtask 4 (30 points): N≤200000N\le200000, R≤25000R\le25000, Q≤200000Q\le200000; no additional conditions.

Conditions shared by all subtasks: For every group: 1≤N≤2000001\le N\le200000, 2≤R≤250002\le R\le25000, 1≤Q≤2000001\le Q\le200000, 1≤Hk≤R1\le H_k\le R; 1≤Sk<k1\le S_k<k for k≥2k\ge2; 1≤r1,r2≤R1\le r_1,r_2\le R, with r1≠r2r_1\ne r_2. Every query answer is guaranteed to be less than 10910^9.

Examples

Input

6 3 4
1
1 2
1 3
2 3
2 3
5 1
1 2
1 3
2 3
3 1

Output

1
3
2
1

Explanation

The tree has 11 as the root, 2,32,3 as its children, 4,54,5 reporting to 22, and 66 reporting to 55. Region IDs are 1,2,3,3,3,11,2,3,3,3,1. Query (1,2)(1,2) counts only (1,2)(1,2): 11. Query (1,3)(1,3) counts (1,3),(1,4),(1,5)(1,3),(1,4),(1,5): 33. Query (2,3)(2,3) counts (2,4),(2,5)(2,4),(2,5): 22. Query (3,1)(3,1) counts (5,6)(5,6): 11.