You are given a tree with n nodes, where each edge in the tree has a corresponding…
- User
You are given a tree with n nodes, where each edge in the tree has a corresponding weight denoting the length of each edge. The nodes in the tree are colored either black or white. Your task is to calculate the sum of distances between every pair of black nodes in the tree. Let B = {b1, b2, ...} a set of black nodes, then the answer is formulated as: |B|-1 |B| Ans = ∑ ∑dist(bi , bj ) i=1 j=i+1
where |B| denotes the number of the black nodes in the tree, and dist(bi, bj ) is the length of the simple path from the i-th to j-th black node. Write a Python program to calculate the sum of distances on the tree between every pair of black nodes Ans in the given tree. 1.2 Input The first line contains an integer n, representing the number of nodes in the tree. The second line contains n space-separated integers {c1, c2, . . . , ci, . . . , cn} where ciis either 0 or 1. ci = 1 indicates that the i-th node is black, and ci = 0 indicates that the i-th node is white. The following n − 1 lines, {l1, l2, . . . , lp, . . . , ln−1}, denoting the structure of the tree follow, each line lp contains 2 integers qp and wp, denoting an edge of length wp between the p + 1-th node and the qp-th node. 1.3 Output Output the sum of distances for every pair of black nodes in the tree.
- Assistant
Here is one possible solution:
def dfs(node, parent, weights, blacks, black_count, dist_sum): dist_from_parent = 0 for child, weight in weights[node]: if child != parent: dist_from_parent += dfs(child, node, weights, blacks, black_count, dist_sum) if blacks[node]: dist_sum[0] += dist_from_parent black_count[0] += 1 return dist_from_parent + dist_from_parent + (black_count[0] - 1) def calculate_sum_of_distances(n, colors, edges): # create adjacency list for the tree structure weights = [[] for _ in range(n)] for i in range(n - 1): a, b = edges[i] weights[a].append((b, 1)) weights[b].append((a, 1)) # convert colors list into a boolean array blacks = [False] * n for i, color in enumerate(colors): if color == 1: blacks[i] = True black_count = [0] dist_sum = [0] dfs(0, -1, weights, blacks, black_count, dist_sum) return dist_sum[0] # example usage n = 5 colors = [1, 1, 0, 0, 1] edges = [(0, 1), (1, 2), (2, 3), (2, 4)] sum_of_distances = calculate_sum_of_distances(n, colors, edges) print(sum_of_distances)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.