Cities
InterviewTime limit2sMemory limit1024 MB
Given a tree with N nodes, count the unordered pairs of cities whose unique path contains exactly K edges.
- Level
Medium7 of 10
- Topics
- Tree, DFS, Divide and conquer, Prefix sum
- Solved
- No attempts yet
Problem
In a far away kingdom, there are cities numbered between and . The cities are connected by two-way roads. Each road has the same length, and connects exactly two cities, so there is a unique path between any pair of cities.
For any two cities and , let be the number of roads on the unique path between cities and . Given an integer , for how many pairs of cities is ?
Input
The sample judge reads input in the following format:
- line :
N K - line :
F[0] F[1] .. F[N - 2] - line :
T[0] T[1] .. T[N - 2]
Output
The sample judge will write a single line with the return value of paths(N, K, F, T).