KatInterview

Right-Triangle Distance Vertices in a Tree

Trees & GraphsAuto-graded · 20 test cases
MediumAuto-gradedTrees & Graphsbfstreegraph-traversal

Last updated

Compute distances in a tree from three marked vertices and count the other vertices whose three distances form a right-triangle (Pythagorean) triple.

Right-Triangle Distance Vertices

You are given a tree with n vertices labeled 1 through n. The tree is undirected and unweighted, and it is described by a list edges of n - 1 pairs. Each pair [u, v] is an edge joining u and v. You are also given three different marked vertices x, y and z.

Call a vertex v special if both of the following hold:

  1. v is not one of the marked vertices (v != x, v != y, v != z). Equivalently, its distances to all three marked vertices are strictly positive.
  2. Let the numbers of edges on the paths from v to x, y and z be sorted as a <= b <= c. Then a * a + b * b == c * c.

Return how many vertices of the tree are special.

Function

Implement count_special_vertices(n, edges, x, y, z), which returns a single integer.

Input

  • n: the number of vertices.
  • edges: a list of n - 1 pairs [u, v], each an undirected edge.
  • x, y, z: three pairwise distinct marked vertices.

Output

  • An integer, the number of special vertices. If there are none, return 0.

Constraints

  • 3 <= n <= 10^5
  • len(edges) == n - 1
  • 1 <= edges[i][0], edges[i][1] <= n
  • The edges form a valid connected tree.
  • 1 <= x, y, z <= n, and x, y, z are pairwise distinct.
  • The tree may be a long chain, so a deeply recursive traversal can exceed the recursion limit.

Examples

Example 1

Input: count_special_vertices(8, [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [3, 7], [7, 8]], 4, 8, 6)

Output: 1

Example 2

Input: count_special_vertices(4, [[1, 2], [2, 3], [3, 4]], 1, 2, 3)

Output: 0

Hints

Hint 1

Computing the distance from each vertex to each marked vertex with a separate search is too slow. Think about running a search from the marked vertices instead.

Hint 2

Run one breadth-first search from each of x, y and z. Together they give all three distances for every vertex in linear time.

Hint 3

Exclude the marked vertices explicitly, since a distance of 0 could otherwise satisfy a^2 + b^2 = c^2 with a = 0. Use an iterative traversal to avoid recursion depth problems.