Approach
To solve this problem, we need to find the sum of all edges in a tree structure given as input. The tree is represented with nodes and edges where each edge has a specified weight. The goal is to compute the total sum of these weights.
- Understanding the Problem: The problem involves a tree structure with
Nnodes andN-1edges. Each edge has a weight, and we need to sum all these weights. - Input Handling: The input consists of the number of nodes
Nfollowed byN-1edges. Each edge is given in the formstart,end, andweight. - Summing Weights: We read each edge, extract its weight, and accumulate the sum of all these weights.
- Edge Cases: If
Nis 1, the tree consists of a single node with no edges, so the sum of weights is 0. For other cases, we read the edges and compute the sum as described.
Solution Code
n = int(input())
total = 0
for _ in range(n - 1):
a, b, c = map(int, input().split())
total += c
print(total)
Explanation
- Reading Input: The first line of input is the number of nodes
n. The next lines contain the edges of the tree. - Summing Weights: For each edge read, we extract the start node, end node, and weight. We add the weight to a running total.
- Output the Result: After processing all edges, the total sum of weights is printed.
This approach efficiently processes the input and computes the required sum, handling all edge cases including when the tree has only one node. The solution is optimal with a time complexity of O(N), where N is the number of nodes, as we process each node exactly once.

@版权声明
转载原创文章请注明转载自科学上网加速器下载|免费VPN客户端下载,高速梯子、全球机场节点、稳定网络连接推荐,网站地址:https://wap.qsxwjmr.cn/