#include using namespace std; #define ll long long #define all(x) x.begin(),x.end() #define rep(i,a,b) for(int i=a;i<=b;i++) #define rep_r(i,a,b) for(int i=a;i>=b;i--) #define each(a,x) for (auto& x : a) using pi = pair; using pl = pair; using vi = vector; using vl = vector; #define sz(x) int(x.size()) #define so(x) sort(all(x)) #define so_r(x) sort(all(x),greater()) #define lb lower_bound #define ub upper_bound const char nl = '\n'; int dx[4] = {1,-1,0,0}; int dy[4] = {0,0,1,-1}; int bit_cnt(int x){ return __builtin_popcount(x); } ll bex(ll a, ll b, ll mod = 1e9 + 7){ll res = 1LL; while(b){ if (b&1) res = res * a % mod; a = a * a % mod; b >>= 1;} return res;} template bool chmax(t&a,u b){if(a bool chmin(t&a,u b){if(b edges; // https://yukicoder.me/problems/no/2200 // De bai: Cho do thi vo huong co trong so co N dinh va M canh // Cost de di tu u -> v = min of (max_edge in path) for path in all_paths from u -> v // Solve: Su dung kruskal tim MST // Trong bai nay ta chi quan tam toi cac canh thuoc MST, cac canh khong thuoc MST ta ignore // why? : gia su path (1,3) tren MST = 1 -> 2 -> 3 trong do 1 -> 2 = 4 va 2 -> 3 = 5 // => 1 -> 3 >= 5 vi neu no nho hon 5 thi da co the noi thang tu 1 -> 3 roi vector fa, sz; int find(int u) {return (u == fa[u] ? u : fa[u] = find(fa[u]));} bool same(int u, int v){ u = find(u); v = find(v); return u == v; } void merge(int u, int v){ u = find(u); v = find(v); if (u == v) return; if (sz[u] < sz[v]) swap(u,v); sz[u] += sz[v]; fa[v] = u; } void solve(){ cin >> n >> m; fa.resize(n+1); sz.resize(n+1); rep(i,1,n) fa[i] = i, sz[i] = 1; rep(i,1,m){ int u,v; ll w; cin >> u >> v >> w; edges.push_back({w,u,v}); } sort(all(edges)); ll ans = 0; each(edges,ed){ ll w = ed[0]; int u = ed[1], v = ed[2]; if (same(u,v)) continue; ans += w * sz[find(u)] * sz[find(v)]; merge(u,v); } cout << ans << nl; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int t = 1; // cin >> t; while (t--){ solve(); } }