I - Black Family Tree


  • محدودیت زمان: ۱ ثانیه
  • محدودیت حافظه: ۲۵۶ مگابایت

A Time-Turner is a magical device used to travel back in time, spend some time there, and then get back to the current time.

Rose Granger has found a Time-Turner in the libraries of Hogwarts and took it upon herself to go back in time and take out some members of the Black family, in order to save the lives of muggles (humans without any magical ability).

The Black family has nn members, numbered 11 to nn in order of being born. Member 11 is the first member of the Black family with a recorded history. For each ii (2in2 \leq i \leq n), member i is a direct descendant of member pip_i (1pi1 \leq p_i < ii). i.e., member pip_i and all of his/her ancestors are an ancestor of member ii. It is also written in the books that the ithi-th member of the Black family is responsible for the death of cic_i muggles.

Now Rose has q options. The jthj-th option is to use the Time-Turner to go back in time and take out all the members from aja_j to bjb_j (ajbja_j \leq b_j) and then come back to the current time. As a consequence of this action, any member of the Black family who has an ancestor among members aja_j to bjb_j will never be born. For any member i who is among members aja_j to bjb_j (i.e. ajibja_j \leq i \leq b_j), or has an ancestor among members aja_j to bjb_j, Rose will save cic_i lives.

For each option, help Rose to find out how many lives she will save if she takes that option.

ورودی🔗

The first line of the input contains two integers nn and qq (2n1052 \leq n \leq 10^5, 1q1051 \leq q \leq 10^5). The second line contains nn space-separated integers c1c_1 to cnc_n (0ci1040 \leq c_i \leq 10^4). The third line contains n1n-1 integers p2p_2 to pnp_n (1pi<i1 \leq p_i < i). Each of the next q lines contains one option; The jthj-th line contains two integers aja_j and bjb_j (1ajbjn1 \leq a_j \leq b_j \leq n).

خروجی🔗

For each jj (1jq1 \leq j \leq q), output the number of lives Rose will save if she takes the jthj-th option.

مثال🔗

ورودی نمونه ۱🔗

6 5
1 2 4 8 16 32
1 2 2 1 5
1 1
2 3
4 5
2 6
6 6
Plain text

خروجی نمونه ۱🔗

63
14
56
62
32
Plain text
ارسال پاسخ برای این سؤال
در حال حاضر شما دسترسی ندارید.