• + 0 comments

    pyhon

    from collections import deque
    
    def treeFlow(n, tree):
        # Write your code here
        graph = [[] for _ in range(500010)]
        for a, b, w in tree:
            graph[a].append((b,w))
            graph[b].append((a,w))
    
        def bfs(start, dis):
            ans = 0
            qu = deque()
            qu.append((-1, start, 0))
            while qu:
                bef, cur, dis = qu.popleft()
                for nex_node, weight in graph[cur]:
                    if nex_node == bef:
                        continue
                    x = dis+weight
                    qu.append((cur, nex_node, x))
                    ans += x
            return ans
            
        answer = min(bfs(1, 0), bfs(n, 0))
        return answer