#include #include struct edge { int from, to, weight; }; bool operator<(const edge& x, const edge& y) { return x.weight < y.weight; } int *parent_of; int get_parent(int node) { if (parent_of[node] == 0) return node; // Change the parent of all intermediate nodes for faster subsequent searches return parent_of[node] = get_parent(parent_of[node]); } int main() { int n, m; scanf("%d %d", &n, &m); parent_of = new int[n + 1]{}; // Initialize with zeroes edge *arr = new edge[m]; long long int result = 0; for (int i = 0; i != m; ++i) { scanf("%d %d %d", &arr[i].from, &arr[i].to, &arr[i].weight); result += arr[i].weight; } std::sort(arr, arr + m); int edge_count = 1; int idx = 0; int p1, p2; while (edge_count < n && idx != m) { p1 = get_parent(arr[idx].from); p2 = get_parent(arr[idx].to); if (p1 != p2) // Edge doesn't close a cycle, so the pick it { parent_of[p1] = p2; result -= arr[idx].weight; ++edge_count; } ++idx; } if (edge_count == n) printf("%lld\n", result); else printf("-1\n"); }