PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000176. Cặp đỉnh tương tự (Similar Pair)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Cặp đỉnh tương tự (Similar Pair)

Similar Pair

Source: HackerRank

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a rooted, parent-to-child directed tree on NN distinctly labeled vertices 1,2,…,N1,2,\ldots,N. Exactly one vertex has no parent, and every other vertex has one parent. An ordered pair (u,v)(u,v) is called similar if uu is a proper ancestor of vv and ∣u−v∣≤K|u-v|\le K. Count all such pairs. Close labels alone do not qualify unless the ancestry relation holds.

Input

The first line contains NN and KK. Each of the next N−1N-1 lines contains two integers u,vu,v, representing a directed edge from parent uu to child vv. The root is not necessarily labeled 11.

Output

Print a single integer: the number of ordered pairs satisfying both conditions.

Subtasks

  • Subtask 1 (20 points): 2≤N≤302\le N\le 30; 0≤K≤N0\le K\le N; exactly N−1N-1 directed edges u→vu\to v with 1≤u,v≤N1\le u,v\le N forming a rooted tree; each non-root vertex has exactly one parent and the root may have any label.
  • Subtask 2 (30 points): 2≤N≤25002\le N\le 2500; 0≤K≤N0\le K\le N; exactly N−1N-1 directed edges u→vu\to v with 1≤u,v≤N1\le u,v\le N forming a rooted tree; each non-root vertex has exactly one parent and the root may have any label.
  • Subtask 3 (50 points): 2≤N≤1000002\le N\le 100000; 0≤K≤N0\le K\le N; exactly N−1N-1 directed edges u→vu\to v with 1≤u,v≤N1\le u,v\le N forming a rooted tree; each non-root vertex has exactly one parent and the root may have any label.

Examples

Example 1

Input

5 2
3 2
3 1
1 4
1 5

Output

4

Explanation

The qualifying proper-ancestor pairs are (3,1), (3,2), (3,4), (3,5). Each satisfies ∣u−v∣≤2|u-v|\le 2. The total is 4. Other pairs are excluded if the nodes are unrelated or if their label difference is too large.

Example 2

Input

5 1
2 1
2 4
4 3
4 5

Output

4

Explanation

The qualifying proper-ancestor pairs are (2,1), (4,3), (2,3), (4,5). Each satisfies ∣u−v∣≤1|u-v|\le 1. The total is 4. Other pairs are excluded if the nodes are unrelated or if their label difference is too large.