#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 7;
long long dp[N][2];
vector<pair<int, int>> adj[N];
int n, k;
void dfs(int u, int par, int parcost) {
  int extra = adj[u].size() - k;
  vector<long long> excess;
  long long ans = 0;
  for (auto pr : adj[u]) {
    int v = pr.first;
    int w = pr.second;
    if (v == par) continue;
    dfs(v, u, w);
    if (dp[v][1] <= dp[v][0])
      ans += dp[v][1], extra--;
    else
      ans += dp[v][0], excess.push_back(dp[v][1] - dp[v][0]);
  }
  sort(excess.begin(), excess.end());
  dp[u][0] = dp[u][1] = ans;
  for (int i = 0; i < extra; i++) dp[u][0] += excess[i];
  for (int i = 0; i < extra - 1; i++) dp[u][1] += excess[i];
  dp[u][1] += parcost;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    cin >> n >> k;
    for (int i = 1; i <= n; i++) {
      adj[i].clear();
    }
    long long total = 0;
    for (int i = 1; i < n; i++) {
      int u, v, c;
      cin >> u >> v >> c;
      total += c;
      adj[u].push_back({v, c});
      adj[v].push_back({u, c});
    }
    dfs(1, 0, 0);
    cout << total - dp[1][0] << endl;
  }
}
