All Tracks Data Structures Trees Binary/ N-ary Trees Problem

Monk and Tree Counting
Tag(s):

Data Structures, Easy-Medium

Problem
Editorial
Analytics

Given a Binary tree $$T$$ consisting of $$N$$ nodes rooted at node $$1$$ and a number $$K$$. each node has a number written on it, where the number written on the $$i^{th}$$ node is $$A[i]$$.

Now, Monk needs to find the number of unordered triplets $$(i,j,k)$$, such that node $$i$$ is an ancestor of node $$j$$ as well as node $$k$$, $$j \ne k$$, and $$A[i]+A[j]+A[k] \ge K$$.
A node $$x$$ is considered an ancestor of another node $$y$$ if $$x$$ is parent of $$y$$ or $$x$$ is an ancestor of parent of $$y$$.

Help Monk for the same.

Input Format :

The first line contains $$2$$ space separated integers $$N$$ and $$K$$. The next line contains $$N$$ 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 represents the parent of node $$i+1$$.

Output Format :

Print the required answer on a single line.

Constraints :

$$ 1 \le N \le 500 $$

$$ 0 \le A[i] ,K \le 10^9 $$

$$ 1 \le parent[i] < i$$, where $$2 \le i \le N$$

Note :

It is guaranteed that the given input forms a valid binary tree.

SAMPLE INPUT
5 6
1 2 3 4 5
1 2 2 1
SAMPLE OUTPUT
7
Explanation

Image of the tree is given below

enter image description here

The triplets forming part of the answer are :

  1. $$ (1,2,3)$$

  2. $$(1,2,4)$$

  3. $$(1,2,5)$$

  4. $$ (1,3,4)$$

  5. $$(1,3,5)$$.

  6. $$ (1,4,5)$$.

  7. $$ (2,3,4)$$

Time Limit: 1.0 sec(s) for each input file.
Memory Limit: 256 MB
Source Limit: 1024 KB
Marking Scheme: Marks are awarded when all the testcases pass.
Allowed Languages: C, C++, C++14, Clojure, C#, D, Erlang, F#, Go, Groovy, Haskell, Java, Java 8, JavaScript(Rhino), JavaScript(Node.js), Julia, Kotlin, Lisp, Lisp (SBCL), Lua, Objective-C, OCaml, Octave, Pascal, Perl, PHP, Python, Python 3, R(RScript), Racket, Ruby, Rust, Scala, Swift, Visual Basic

CODE EDITOR

Initializing Code Editor...
Your Rating:

Contributor

This Problem was Asked in

HackerEarth

Challenge Name

CodeMonk (Trees)

OTHER PROBLEMS OF THIS CHALLENGE
Notifications
View All Notifications