def solution(n, costs):
    answer = 0
    costs.sort(key=lambda x: x[2])
    visited = [0] * n
    visited[0] = 1

    while sum(visited) != n:
        for cost in costs:
            s, e, c = cost

            if visited[s] or visited[e]:
                if visited[s] and visited[e]:
                    continue
                
                else:
                    visited[s] = 1
                    visited[e] = 1
                    answer += c
                    break
    
    return answer

if __name__ == "__main__":
    
    #Test case 1
    n = 4
    costs = [[0,1,1],[0,2,2],[1,2,5],[1,3,1],[2,3,8]]
    #result 4

    print(solution(n, costs))