Sum of Perfect Square Ancestors

You are given an undirected tree rooted at node 0 consisting of n nodes, numbered from 0 to n - 1. The tree is represented by a 2D array edges of length n - 1, where edges[i] = [u, v] indicates an edge between node u and node v.

You are also given an integer array nums of length n, where nums[i] represents the positive integer value assigned to node i.

For each node i, let ti be the total number of its ancestors such that the product nums[i] * nums[ancestor] results in a perfect square.

Return the total sum of all ti values across all nodes in the range [1, n - 1].

(Note: An ancestor of node i is any node on the shortest path from node i to the root node 0, excluding node i itself.)

Example 1:

Input: n = 3, edges = [[0,1], [0,2]], nums = [9, 1, 4]

Output: 2

Explanation:

Node 1: Ancestor is 0. nums[1] * nums[0] = 1 * 9 = 9 (Perfect square). t1 = 1.

Node 2: Ancestor is 0. nums[2] * nums[0] = 4 * 9 = 36 (Perfect square). t2 = 1. Total sum = 1 + 1 = 2.

Example 2:

Input: n = 2, edges = [[0,1]], nums = [3, 4]

Output: 0

Explanation:

Node 1: Ancestor is 0. nums[1] * nums[0] = 4 * 3 = 12 (Not a perfect square). t1 = 0. Total sum = 0.

Now Your Turn!

Pick the correct output for the given input

Input: n = 2, edges = [[0,1]], nums = [3, 12]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n <= 105
  • edges.length == n - 1
  • edges[i] = [u, v]
  • 0 <= u, v <= n - 1
  • nums.length == n
  • 1 <= nums[i] <= 105
  • The input guarantees that edges represents a valid tree.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
long long sumOfAncestors(int n, vector<vector<int>>& edges, vector<int>& nums) {
}
};
Test Case

Input:

Edges
N
Nums