El Nino !

3.3

20 votes
Algorithms, Depth First Search, Easy, Graphs
Problem

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 (Ui,Vi,Ki) and (Uj,Vj,Kj) are considered to be distinct, if UiUj or ViVj or KiKj.

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 ith integer denotes A[i].

The next line contains N1 space separated integers, where the ith 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 :

1N,M200,000

0A[i]109 , where 1iM

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

The triplets for the sample test are :

  1. (1,2,1)

  2. (1,3,2)

  3. (1,4,3)

  4. (2,3,1)

  5. (2,4,2)

  6. (2,5,3)

  7. (3,4,1)

  8. (3,5,2)

  9. (4,5,1)

Editor Image

?