#include<bits/stdc++.h>
using namespace std;
struct edge{
int x;
int y;
int val;
}a[5009];
int n,m;
long long ans;
bool hav_ans=true;
int p[5009];
int get_fu(int x){
while(x!=p[x]) x=p[x]=p[p[x]];
return x;
}
bool cmp(edge a,edge b){
return a.val<b.val;
}
void kruskal(){
int f1,f2,k=0;
for(int i=1;i<=m;i++){
f1=get_fu(a[i].x);
f2=get_fu(a[i].y);
if(f1!=f2){
ans+=a[i].val;
cout<<a[i].x<<" "<<a[i].y<<" "<<a[i].val<<endl;
p[f1]=f2;
k++;
if(k==n-1) break;
}
}
/*
if(k<n-1){
cout<<"orz";
hav_ans=false;
}
*/
return;
}
int main(){
freopen("P3366_2.in","r",stdin);
cin>>n>>m;
for(int i=1;i<=n;i++) p[i]=i;
for(int i=1;i<=m;i++){
cin>>a[i].x>>a[i].y>>a[i].val;
}
sort(a+1,a+m+1,cmp);
kruskal();
cout<<ans;
}