#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int N, K;
long long dp[500001][2];
vector<pair<int, int>> adj[500001];
void dfs(int node, int par, int costPar) {
  for (auto it : adj[node])
    if (it.first != par) dfs(it.first, node, it.second);
  dp[node][0] = 0;
  vector<int> v;
  for (auto it : adj[node]) {
    if (it.first != par) {
      dp[node][0] += dp[it.first][0];
      v.push_back(-(dp[it.first][1] - dp[it.first][0]));
    }
  }
  dp[node][1] = dp[node][0] + costPar;
  sort(v.begin(), v.end());
  for (int i = 0; i < min((int)v.size(), K); i++) dp[node][0] -= min(0, v[i]);
  for (int i = 0; i < min((int)v.size(), K - 1); i++)
    dp[node][1] -= min(0, v[i]);
}
void solve() {
  scanf("%d%d", &N, &K);
  for (int i = 1; i <= N; i++) adj[i].clear();
  for (int j = 0; j < N - 1; j++) {
    int A, B, C;
    scanf("%d%d%d", &A, &B, &C);
    adj[A].push_back({B, C});
    adj[B].push_back({A, C});
  }
  dfs(1, 1, 0);
  cout << dp[1][0] << endl;
}
int main() {
  int Q;
  scanf("%d", &Q);
  while (Q--) solve();
  return 0;
}
