/* -*- coding: utf-8 -*- * * 2200.cc: No.2200 Weird Shortest Path - yukicoder */ #include #include #include using namespace std; /* constant */ const int MAX_N = 100000; const int MAX_M = 200000; /* typedef */ typedef long long ll; struct Edge { int u, v, w; Edge() {} Edge(int _u, int _v, int _w): u(_u), v(_v), w(_w) {} void read() { scanf("%d%d%d", &u, &v, &w); u--, v--; } bool operator<(const Edge &e) const { return w < e.w; } }; struct UFT { vector links, ranks, sizes; UFT() {} void init(int n) { links.resize(n); for (int i = 0; i < n; i++) links[i] = i; ranks.assign(n, 1); sizes.assign(n, 1); } int root(int i) { int i0 = i; while (links[i0] != i0) i0 = links[i0]; return (links[i] = i0); } int rank(int i) { return ranks[root(i)]; } int size(int i) { return sizes[root(i)]; } bool same(int i, int j) { return root(i) == root(j); } int merge(int i0, int i1) { int r0 = root(i0), r1 = root(i1), mr; if (r0 == r1) return r0; if (ranks[r0] == ranks[r1]) { links[r1] = r0; sizes[r0] += sizes[r1]; ranks[r0]++; mr = r0; } else if (ranks[r0] > ranks[r1]) { links[r1] = r0; sizes[r0] += sizes[r1]; mr = r0; } else { links[r0] = r1; sizes[r1] += sizes[r0]; mr = r1; } return mr; } }; /* global variables */ Edge es[MAX_M]; UFT uft; /* subroutines */ /* main */ int main() { int n, m; scanf("%d%d", &n, &m); for (int i = 0; i < m; i++) es[i].read(); sort(es, es + m); uft.init(n); ll sum = 0; for (int i = 0; i < m; i++) { Edge &e = es[i]; if (! uft.same(e.u, e.v)) { sum += (ll)e.w * uft.size(e.u) * uft.size(e.v); uft.merge(e.u, e.v); } } printf("%lld\n", sum); return 0; }