#include <iostream>
#include <stdlib.h>
#include <memory.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
#define MAX 100000
#define min( a, b) (a)<(b)?(a):(b)
int N=0,M=0;
typedef struct Graph
{
int matrix[1010][1010];
bool visited[1010];
// int vNum;
}* pGraph;
int cost[3010];
bool used[3010];
pGraph g;
void Creat()
{
g=(pGraph)malloc(sizeof(struct Graph));
// g->vNum=N;
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
g->matrix[i][j]=MAX;
}
cost[i]=MAX;
g->visited[i]=false;
}
for(int i=0; i<M; i++)
{
int c1,c2,c;
cin>>c1>>c2>>c;
g->matrix[c1-1][c2-1]=g->matrix[c2-1][c1-1]=c;//
}
}
void DFS(int v)
{
if(g->visited[v]) return;
g->visited[v]=true;
for(int i=0; i<N; i++)
{
if(!g->visited[i] && g->matrix[v][i] != MAX)
{
DFS(i);
}
}
}
int Prim()
{
int res=0;
for(int j=0; j<N; j++)
{
// cost[j]=g->matrix[0][j];
cost[j]=MAX;
used[j]=false;
}
cost[0]=0;
while(1)
{
int pos=-1;
for(int i=0; i<N; i++)
{
if(!used[i] && (pos==-1 || cost[i]<cost[pos]))
{
pos=i;
}
}
if(pos==-1) break;
used[pos]=true;
res+=cost[pos];
for(int i=0; i<N; i++)
{
cost[i]=min(cost[i],g->matrix[pos][i]);
}
}
return res;
// for(int i=1; i<N; i++)
// {
// for(j=1; j<N; j++)
// {
// if(cost[j]!=0 && min>cost[j])
// {
// min=cost[j];
// pos=j;//找到最小的位置
// }
// }
// if(pos == -1)//没有找到
// {
// break;
// }
// res+=cost[pos];
// cost[pos]=0;
// for(j=1; j<N; j++)
// {
// if(cost[j] !=0 && g->matrix[pos][j]<cost[j])
// {
// cost[j]=g->matrix[pos][j];
// }
// }
// }
// return res;
}
void printg()
{
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
cout<<g->matrix[i][j]<<" ";
}
// cout<<g->visited[i];
cout<<endl;
}
}
int main(int argc, char** argv) {
int ans;
cin>>N>>M;
Creat();
// printg();
DFS(0);
for(int i=0; i<N; i++)
{
if(!g->visited[i])
{
cout<<-1<<endl;
return 0;
}
}
ans=Prim();
cout<<ans<<endl;
return 0;
}