#include <bits/stdc++.h>
using namespace std;
const long long inf = (long long)1e18;
const long long mod = (long long)1e9 + 7;
const double eps = (double)1e-9;
const double pi = acos(-1.0);
const int dx[] = {0, 0, 1, 0, -1};
const int dy[] = {0, 1, 0, -1, 0};
const int N = 500500;
int n, k;
vector<pair<int, int> > g[N];
long long dp[N], W[N];
void dfs(int v, int pr = -1) {
  dp[v] = 0;
  vector<long long> u;
  for (auto to : g[v]) {
    if (to.first == pr) continue;
    dfs(to.first, v);
    dp[v] += dp[to.first] + W[to.first];
    if (-W[to.first] + to.second > 0) u.push_back(-W[to.first] + to.second);
  }
  sort(u.begin(), u.end());
  reverse(u.begin(), u.end());
  for (int i = 0; i < min(k - 1, (int)u.size()); ++i) dp[v] += u[i];
  if (k <= (int)u.size())
    W[v] = u[k - 1];
  else
    W[v] = 0;
}
void solve() {
  cin >> n >> k;
  for (int i = 1; i <= n; ++i) g[i].clear();
  for (int i = 1; i < n; ++i) {
    int x, y, w;
    cin >> x >> y >> w;
    g[x].push_back(make_pair(y, w));
    g[y].push_back(make_pair(x, w));
  }
  dfs(1);
  cout << dp[1] + W[1] << endl;
}
int main() {
  cin.tie(NULL);
  cout.tie(NULL);
  ios_base::sync_with_stdio(false);
  int T;
  cin >> T;
  while (T--) solve();
  return 0;
}
