Stevie : "The best part about Christmas is a Christmas tree. Fantastic to play with". A great goalscorer is one who is remembered even years after he left, just like this guy :
You have been given a tree T consisting of N nodes rooted at node 1 and an array A consisting of M distinct integers.
Now, you need to find the number of distinct triplets \((U,V,K)\) in tree T such that node V lies in the subtree rooted at node U, and the distance between them is exactly \(A[K]\). We call the distance between 2 nodes to be the number of edges lying in the shortest path among them.
2 triplets \((U_i,V_i,K_i)\) and \((U_j,V_j,K_j)\) are considered to be distinct, if \(U_i \ne U_j\) or \(V_i \ne V_j \) or \(K_i \ne K_j\).
Can you do it ?
Input Format :
The first line contains 2 space separated integers N and M.
The next line contains M pairwise distinct space separated integers, where the \(i^{th}\) integer denotes \(A[i]\).
The next line contains \(N-1\) space separated integers, where the \(i^{th}\) integer denotes the parent of node \(i+1\) in tree T.
Output Format:
Print a single integer denoting the required number of valid triplets in tree T
Constraints :
\( 1 \le N,M \le 200,000 \)
\( 0 \le A[i] \le 10^9 \) , where \( 1 \le i \le M \)
The triplets for the sample test are :
-
\((1,2,1)\)
-
\((1,3,2)\)
-
\( (1,4,3) \)
-
\( (2,3,1) \)
-
\( (2,4,2) \)
-
\( (2,5,3) \)
-
\( (3,4,1) \)
-
\( (3,5,2) \)
-
\( (4,5,1) \)
Please login to use the editor
You need to be logged in to access the code editor
Loading...
Please wait while we load the editor
Login to unlock the editorial
Please login to use the editor
You need to be logged in to access the code editor
Loading...
Please wait while we load the editor