def f(a): b=a a=A[a] while type(a)!=int: b=int(a) a=A[int(a)] return [a,b] n,m=map(int,input().split()) D=[] A=[None]+[1]*n for i in range(1,m+1): a,b,w=map(int,input().split()) D.append([w,a,b]) D.sort() D=[None]+D ans=0 for i in range(1,m+1): q=f(D[i][1]) w=f(D[i][2]) if q[1]==w[1]: div=0 else: div=q[0]*w[0] A[q[1]]+=A[w[1]] A[w[1]]=str(q[1]) ans+=D[i][0]*div print(ans)