#P7331. Dream and the Multiverse REMATCH

Dream and the Multiverse REMATCH

Background

Link

I have gone over the scenarios in my head,

and there are 6.96969 billion outcomes, and only one of them -

- do I win.

Problem Description

Dream abstracts the fabric of spacetime as a directed rooted tree (arborescence) with NN nodes (numbered 11 through NN). Node 11 is the root and for each ii (1≤i≤N−11 \le i \le N-1), the parent of node i+1i+1 is fif_i. All edges of this tree are directed away from the root.

Then, Dream employs a magical superpower and adds MM directed edges to this tree in such a way that the resulting directed graph remains acyclic (a DAG).

Let's call a node of this DAG an event and further call a simple path on this DAG an era. Dream considers a pair of events (i,j)(i,j) to be plausible if there is an era whose first event is ii and last event is jj. Note that i<ji \lt j does not have to hold for a plausible pair.

Dream now wants you to answer QQ queries. In each query, he gives you two positive integers ll and rr, where l≤rl \leq r, and he wishes to know the number of plausible pairs of events (i,j)(i,j) such that l≤i<j≤rl \leq i \lt j \leq r.

Input Format

The first line of the input contains two space-separated integers NN and MM.

The second line contains N−1N-1 space-separated integers f1,f2,…,fN−1f_1, f_2, \ldots, f_{N-1}.

MM lines follow. Each of these lines contains two space-separated integers uu and vv describing an additional edge from node uu to node vv.

The following line contains a single integer QQ.

QQ lines follow. Each of these lines contains two space-separated integers ll and rr describing a query.

Output Format

For each query, print a single line containing one integer ― the number of plausible pairs (i,j)(i,j) such that l≤i<j≤rl \leq i \lt j \leq r.

8 2
1 2 5 1 4 3 3
2 4
4 7
3
4 6
5 7
1 8
2
2
18

Hint

  • 2≤N≤7⋅1052 \leq N \leq 7 \cdot 10^5
  • 1≤Q≤7⋅1051 \leq Q \leq 7 \cdot 10^5
  • 0≤M≤200 \leq M \leq 20
  • 1≤fi≤N1 \le f_i \le N for each valid ii
  • 1≤u,v≤N1 \le u, v \le N
  • the graph described on the input is acyclic
  • 1≤l≤r≤N1 \le l \le r \le N

Subtasks

Subtask #1 (17 points): N,Q≤3⋅105N,Q\le3\cdot 10^5

Subtask #2 (83 points): original constraints