#include <bits/stdc++.h>
using namespace std;
vector<vector<pair<int, int> > > graph(500005, vector<pair<int, int> >());
bool was[500005];
long long int dp[500005][2];
int n, k;
void dfs(int v) {
  was[v] = true;
  vector<long long int> diffs;
  long long int sum = 0;
  for (auto ed : graph[v]) {
    int u = ed.first;
    if (!was[u]) {
      dfs(u);
      diffs.push_back(dp[u][1] + ed.second - dp[u][0]);
      sum += dp[u][0];
    }
  }
  sort(diffs.begin(), diffs.end());
  for (int i = 0; i < k - 1 && i < diffs.size(); i++) {
    sum += max(diffs[diffs.size() - i - 1], 0LL);
  }
  dp[v][1] = sum;
  if (diffs.size() >= k) {
    sum += max(diffs[diffs.size() - k], 0LL);
  }
  dp[v][0] = sum;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  int T;
  cin >> T;
  while (T--) {
    cin >> n >> k;
    for (int i = 1; i <= n; i++) {
      graph[i].clear();
      was[i] = false;
      dp[i][0] = dp[i][1] = 0;
    }
    for (int i = 1; i < n; i++) {
      int a, b, c;
      cin >> a >> b >> c;
      graph[a].push_back({b, c});
      graph[b].push_back({a, c});
    }
    dfs(1);
    cout << dp[1][0] << "\n";
  }
  return 0;
}
