// #pragma GCC optimize("O3")
// #pragma GCC optimize("unroll-loops")
// #pragma GCC target("avx2,bmi,bmi2,popcnt,lzcnt")
#include<bits/stdc++.h>
using namespace std;
#define i64 long long
#define int long long
#define mp make_pair
#define pb push_back
#define all(x) (x).begin(), (x).end()
const int MAXN = 5e5 + 5;
const i64 INF = LLONG_MAX/2;
struct DSU{
int N, ccp;
vector<int> lab, sz;
vector<int64_t> sum;
DSU(int _N) : N(_N), ccp(_N), sum(N + 5, 0), sz(_N + 5, 1), lab(_N + 5) {
for (int i = 1; i <= N; i ++) {
lab[i] = i;
}
};
int findLab(int u) { return (u == lab[u] ? u : lab[u] = findLab(lab[u])); }
bool unite(int u, int v, int64_t w) {
int labu = findLab(u);
int labv = findLab(v);
if (labu == labv) return false;
if (sz[labu] < sz[labv]) swap(labu, labv);
sz[labu] += sz[labv];
lab[labv] = labu;
sum[labu] += sum[labv] + w;
ccp --;
return true;
}
};
int N, M;
struct Edge {
int u, v, w, id;
};
vector<pair<int, int>> G[MAXN];
int h[MAXN], up[MAXN][22], mx[MAXN][22];
void dfs(int u) {
for (auto [v, w] : G[u]) {
if (v != up[u][0]) {
h[v] = h[u] + 1;
up[v][0] = u;
mx[v][0] = w;
for (int j = 1; j <= 20; j ++) {
up[v][j] = up[up[v][j - 1]][j - 1];
mx[v][j] = max(mx[v][j - 1], mx[up[v][j - 1]][j - 1]);
}
dfs(v);
}
}
}
int LCA(int u, int v) {
int ans = 0;
if (h[u] < h[v]) swap(u, v);
int gap = h[u] - h[v];
for (int j = 0; (1 << j) <= gap; j ++) {
if (gap >> j & 1) {
ans = max(ans, mx[u][j]);
u = up[u][j];
}
}
if (u == v) {
ans = max(ans, mx[u][0]);
return ans;
}
for (int j = 20; j >= 0; j --) {
if (up[u][j] != up[v][j]) {
ans = max(ans, mx[u][j]);
ans = max(ans, mx[v][j]);
u = up[u][j];
v = up[v][j];
}
}
ans = max(ans, mx[u][0]);
ans = max(ans, mx[v][0]);
u = up[u][0];
ans = max(ans, mx[u][0]);
return ans;
}
void Solve(void) {
cin >> N >> M;
vector<Edge> edges;
vector<bool> used(M + 2, false);
for (int i = 1; i <= M; i ++) {
int u, v, w; cin >> u >> v >> w;
edges.pb({u, v, w, i});
}
sort(all(edges), [&](Edge &a, Edge &b) {
return a.w < b.w;
});
DSU MST(N);
for (auto [u, v, w, id] : edges) {
if (MST.unite(u, v, w)) {
used[id] = true;
}
}
DSU MST2(N);
for (auto [u, v, w, id] : edges) {
if (used[id]) continue;
if (MST.unite(u, v, w)) {
G[u].pb(mp(v, w));
G[v].pb(mp(u, w));
}
}
if (MST2.ccp != 1) { cout << -1 << "\n"; return; }
dfs(1);
i64 ans = 0;
for (auto [u, w, w, id] : edges) {
if (used[id]) {
ans += LCA(u, v) + 1 - w;
}
}
cout << ans << "\n";
}
signed main() {
ios_base::sync_with_stdio(false); cin.tie(0);
cout << fixed << setprecision(10);
int Tests = 1; // cin >> Tests;
while (Tests --) {
Solve();
}
}