Similar pairs in Tree

3.4

7 votes
Problem

You are given a tree where each node is labeled from 1 to n. How many similar pair(s) are there in this tree?

A pair (A,B) is a similar pair if the following are true:

  • node A is the ancestor of node B

  • abs(A−B)≤T

Input format:

The first line of the input contains two integers, n and T. This is followed by n−1 lines, each containing two integers si and ei where node si is a parent to node ei.

Output format:

Output a single integer which denotes the number of similar pairs in the tree.

Constraints:

1≤n≤100000

0≤T≤n

1≤si, ei ≤n

Register for Algorithms in IndiaHacks

Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

The similar pairs are: (3, 2) (3, 1) (3, 4) (3, 5). enter image description here

Editor Image

?