El Nino !
Practice
3.3 (20 votes)
Algorithms
Depth first search
Easy
Graphs
Problem
78% Success 3296 Attempts 20 Points 1s Time Limit 256MB Memory 1024 KB Max Code

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 :

                                                                 enter image description here

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 \)

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

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:20
17 votes
Tags:
AlgorithmsBreadth First SearchDepth First SearchEasyGraphs
Points:20
17 votes
Tags:
AlgorithmsDepth First SearchEasyGraphs
Points:20
121 votes
Tags:
ApprovedEasyMathNumber theory