#include #include #include #include #include #include using namespace std; #define int long long struct UnionFind { private: int n; vector par,siz; public: UnionFind(int n) :n(n),par(n,-1),siz(n,1) {} int root(int u) { assert(0 <= u && u < n); return (par[u] < 0 ? u:par[u] = root(par[u])); } bool same(int u,int v) { assert(0 <= u && u < n && 0 <= v && v < n); return root(u) == root(v); } bool unite(int u,int v) { assert(0 <= u && u < n && 0 <= v && v < n); u = root(u),v = root(v); if(u == v) return false; if(siz[u] < siz[v]) swap(u,v); siz[u] += siz[v]; par[v] = u; return true; } int size(int u) { assert(0 <= u && u < n); return siz[root(u)]; } vector> components() { vector> ret(n); for(int u = 0;u < n;u++) ret[root(u)].push_back(u); ret.erase(remove_if(ret.begin(),ret.end(),[](vector v) { return v.empty();}),ret.end()); return ret; } }; struct edge{ int u, v, c; }; bool cmp(edge a, edge b){ return a.c < b.c; } void solve(){ int n, m; cin >> n >> m; vectore; for(int i = 1; i <= m; i++){ int u, v, c; cin >> u >> v >> c; u--, v--; e.push_back({u, v, c}); } sort(e.begin(), e.end(), cmp); UnionFind dsu(n); long long ans = 0; for(int i = 0; i < m; i++){ if(!dsu.same(e[i].u, e[i].v)){ ans += e[i].c * dsu.size(e[i].u) * dsu.size(e[i].v); dsu.unite(e[i].u, e[i].v); } } cout << ans << '\n'; } signed main(){ ios::sync_with_stdio(false); ios_base::sync_with_stdio(false); cin.tie(0), cout.tie(0); int t = 1; //cin >> t; while(t--){ solve(); } return 0; }