#FT0000176. Cặp đỉnh tương tự (Similar Pair)
Bài tập thuộc lộ trình
Mục lục đề ⌄
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 distinctly labeled vertices . Exactly one vertex has no parent, and every other vertex has one parent. An ordered pair is called similar if is a proper ancestor of and . Count all such pairs. Close labels alone do not qualify unless the ancestry relation holds.
Input
The first line contains and . Each of the next lines contains two integers , representing a directed edge from parent to child . The root is not necessarily labeled .
Output
Print a single integer: the number of ordered pairs satisfying both conditions.
Subtasks
- Subtask 1 (20 points): ; ; exactly directed edges with forming a rooted tree; each non-root vertex has exactly one parent and the root may have any label.
- Subtask 2 (30 points): ; ; exactly directed edges with forming a rooted tree; each non-root vertex has exactly one parent and the root may have any label.
- Subtask 3 (50 points): ; ; exactly directed edges with 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 . 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 . The total is 4. Other pairs are excluded if the nodes are unrelated or if their label difference is too large.