#include #include #include #include #include #define forn(i, n) for(int i = 0; i < (n); ++i) #define INFINITY 9999999 using std::make_pair; using std::min; using std::pair; using std::vector; using std::chrono::high_resolution_clock; using std::chrono::milliseconds; using std::chrono::duration_cast; typedef int cost_t; typedef vector vcost_t; typedef vector vvcost_t; typedef vvcost_t adjacency_matrix; typedef vector vint; typedef pair edge; typedef vector vbool; typedef pair weighted_edge; void initialize(const adjacency_matrix& A, vcost_t& dist) { int n = dist.size(); forn(i, n) { forn(j, n) { dist[i] = min(dist[i], A[i][j]); } } } __attribute__((always_inline)) weighted_edge lightest_edge(const adjacency_matrix& A, const vcost_t& dist, const vbool& rep) { int idx = 0, n = dist.size(); while (!rep[idx]) ++idx; for (int i = idx + 1; i < n; ++i) { if (!rep[i]) continue; if (dist[i] < dist[idx]) idx = i; } cost_t weight = dist[idx]; int target = 0; for (int i = 0; i < n; ++i) { if (!rep[i]) continue; if (A[idx][i] == weight) { target = i; break; } } return weighted_edge(weight, edge(idx, target)); } __attribute__((always_inline)) void contract(const weighted_edge& e, adjacency_matrix& A, vcost_t& dist, vbool& rep) { int n = dist.size(), u = e.second.first, // new parent v = e.second.second; // new child rep[v] = false; dist[u] = INFINITY; for (int i = 0; i < n; ++i) { if (!rep[i]) continue; if (i == u) continue; A[i][u] = A[u][i] = min(A[u][i], A[v][i]); dist[u] = min(dist[u], A[u][i]); } } cost_t kruskal_warnes(adjacency_matrix& A) { int n = A.size(); cost_t total_cost = 0; vcost_t dist(n, INFINITY); vbool rep(n, true); initialize(A, dist); int remaining = n - 1; while (remaining --> 0) { weighted_edge e = lightest_edge(A, dist, rep); total_cost += e.first; contract(e, A, dist, rep); } return total_cost; } int main() { int n, m, u, v; cost_t w; scanf("%d %d", &n, &m); adjacency_matrix A(n, vcost_t(n, INFINITY)); forn (j, m) { scanf("%d %d %d", &w, &u, &v); A[u][v] = A[v][u] = w; } high_resolution_clock c; auto t1 = c.now(); kruskal_warnes(A); auto t2 = c.now(); printf("%ld\n", duration_cast(t2 - t1).count()); }