N, M = map(int, input().split()) ABW = [list(map(int, input().split())) for _ in range(M)] def root(x): if P[x] < 0: return x P[x] = root(P[x]) # 経路圧縮 return P[x] def unite(x, y): x = root(x) y = root(y) if x == y: return if x > y: x, y = y, x P[x] += P[y] P[y] = x def same(x, y): return root(x) == root(y) def size(x): x = root(x) return -P[x] P = [-1] * (N + 1) ABW.sort(key=lambda x: x[2]) ans = 0 for a, b, w in ABW: if not same(a, b): ans += w * size(a) * size(b) unite(a, b) if size(1) == N: print(ans) exit()