#include <iostream>
#include <algorithm>
using namespace std;
struct edge
{
int a, b, cost;
}e[3010];
int sum[1010], tree[1010], res;
int cmp(edge e1, edge e2)
{
return e1.cost < e2.cost;
}
int findroot(int root)
{
if(tree[root] == -1)
{
return root;
}
else
{
tree[root] = findroot(tree[root]);
return tree[root];
}
}
void buildrelation(edge e)
{
int index[2];
index[0] = e.a;
index[1] = e.b;
int i;
for(i = 0; i < 2; i++)
{
index[i] = findroot(index[i]);
}
if(index[0] == index[1])
{
return;
}
int index0 = index[0], index1 = index[1];
if(sum[index1] > sum[index0])
{
index[0] = index1;
index[1] = index0;
}
tree[index1] = index0;
sum[index0] += sum[index1];
res += e.cost;
}
int getrootcount(int n)
{
int i, count = 0;
for(i = 1; i <= n; i++)
{
if(tree[i] == -1)
{
count++;
}
}
return count;
}
int main()
{
int n, m;
scanf("%d%d", &n, &m);
int i;
for(i = 1; i <= m; i++)
{
scanf("%d%d%d", &e[i].a, &e[i].b, &e[i].cost);
}
sort(e + 1, e + m + 1, cmp);
for(i = 1; i <= n; i++)
{
sum[i] = 1;
tree[i] = -1;
}
for(i = 1; i <= m; i++)
{
buildrelation(e[i]);
}
if(getrootcount(n) > 1)
{
printf("-1\n");
return 0;
}
printf("%d\n", res);
system("pause");
return 0;
}