const int inf = 1<<29;
int n, m;
int edge[105][105];
bool vis[105];
int d[105];
struct node
{
int v, c;
node(int _v = 0, int _c = 0):v(_v), c(_c){}
friend bool operator< (node n1, node n2){
return n1.c > n2.c;
}
};
int ans;
void prim(){
priority_queue<node>que;
while(!que.empty()) que.pop();
memset(vis, false, sizeof(vis));
for(int i = 1; i <= n; i++){
d[i] = edge[1][i];
if (d[i] < inf) que.push(node(i, d[i]));
}
vis[1] = true;
ans = 0;
int cnt = 0;
while(!que.empty()){
node tem = que.top();
que.pop();
int v = tem.v;
int c = tem.c;
if (vis[v]) continue;
vis[v] = true;
// printf("v = %d c = %d
", v, c);
ans += c;
cnt++;
if (cnt == n-1) break;
for(int i = 1; i <= n; i++){
if (!vis[i] && edge[v][i] < d[i]){
d[i] = edge[v][i];
que.push(node(i, d[i]));
}
}
}
if (cnt < n-1) ans = -1;
}
int main() {
int t;
int a, b, c;
cin >>t;
while(t--){
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
edge[i][j] = inf;
}
}
for(int i = 1; i <= m; i++){
scanf("%d%d%d", &a, &b, &c);
edge[a][b] = edge[b][a] = c;
}
prim();
printf("%d
", ans);
}
return 0;
}