progress

~/problems / Graphs / BFS / multi-source BFS

Tree nodes whose distances form a Pythagorean triple

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A tree has nodes 0 … n-1; edge i joins tree_from[i] and tree_to[i]. Distance is the number of edges between two nodes.

Given three nodes x, y, z (not necessarily different), sort a node u's distances to them into a <= b <= c. u is Pythagorean if a² + b² == c².

Write count_pythagorean_nodes(n, tree_from, tree_to, x, y, z) -> int: how many nodes are Pythagorean (including x, y, z themselves).

# path 0 - 1 - 2 - 3 - 4 - 5, with x = 0, y = 3, z = 5
count_pythagorean_nodes(6, [0, 1, 2, 3, 4], [1, 2, 3, 4, 5], 0, 3, 5)
# node 3: distances 3, 0, 2 -> 0, 2, 3   0 + 4 != 9   no
# node 5: distances 5, 2, 0 -> 0, 2, 5   no
# node 4: distances 4, 1, 1 -> 1, 1, 4   no     ... the answer is 0

# star: centre 0 joined to 1, 2, 3; x = 1, y = 2, z = 3
count_pythagorean_nodes(4, [0, 0, 0], [1, 2, 3], 1, 2, 3)
# node 0: 1, 1, 1 -> 1 + 1 != 1       no
# node 1: 0, 2, 2 -> 0 + 4 == 4       yes (and likewise nodes 2 and 3)   -> 3

1 <= n <= 2 * 10^5. Squared distances reach 4 * 10^10: use 64-bit integers in C++ or Java.

⭐ Bonus: a speed test on a 200,000-node path earns a star in O(n) without recursion.

Show hint

One BFS from each of x, y, z gives three distance arrays; then check every node.

Topic: BFS / multi-source BFS. Level-by-level search; seed the queue with every source.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc