#include <bits/stdc++.h>
using namespace std;
const long long N = 1e6 + 100;
vector<pair<long long, long long> > a[N];
long long dpu[N];
long long dp[N];
long long n, k;
vector<long long> u[N];
void dfs(long long v, long long p = -1) {
  dp[v] = dpu[v] = 0;
  for (auto P : a[v]) {
    long long u2 = P.first;
    long long w = P.second;
    if (u2 == p) continue;
    dfs(u2, v);
    dp[v] += dp[u2];
    dpu[v] += dp[u2];
    long long val = dpu[u2] + w - dp[u2];
    if (val > 0) u[v].push_back(val);
  }
  sort(u[v].begin(), u[v].end(), greater<long long>());
  for (long long i = 0; i < min(k, (long long)u[v].size()); i++) {
    dp[v] += u[v][i];
    if (i < k - 1) {
      dpu[v] += u[v][i];
    }
  }
  u[v].clear();
}
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  long long t;
  cin >> t;
  for (long long ii = 0; ii < t; ii++) {
    cin >> n >> k;
    for (long long i = 0; i < n; i++) {
      a[i].clear();
      u[i].clear();
    }
    for (long long i = 0, u, v, w; i < n - 1; i++) {
      cin >> u >> v >> w;
      u--;
      v--;
      a[u].push_back(make_pair(v, w));
      a[v].push_back(make_pair(u, w));
    }
    dfs(0);
    cout << dp[0] << "\n";
  }
  return 0;
}
