#include <bits/stdc++.h>
using namespace std;
const long double PI = acos(-1.0);
const long long N = 5e5 + 4;
vector<pair<long long, long long> > adjlist[N];
long long dp[N][2];
long long n, k;
bool cmp(pair<long long, long long> a, pair<long long, long long> b) {
  return a.first - a.second > b.first - b.second;
}
void dfs(long long node, long long par) {
  dp[node][1] = 0;
  dp[node][0] = 0;
  vector<pair<long long, long long> > clist;
  vector<pair<long long, long long> > dps;
  for (auto i : adjlist[node]) {
    if (i.first != par) {
      clist.push_back(i);
      dfs(i.first, node);
    }
  }
  for (auto i : clist) {
    dps.push_back(make_pair((dp[i.first][1] + i.second), (dp[i.first][0])));
  }
  sort(dps.begin(), dps.end(), cmp);
  for (long long i = 0; i < (long long)dps.size(); ++i) {
    if (i < k) {
      dp[node][0] += max(dps[i].first, dps[i].second);
    } else
      dp[node][0] += dps[i].second;
    if (i < k - 1) {
      dp[node][1] += max(dps[i].first, dps[i].second);
    } else
      dp[node][1] += dps[i].second;
  }
}
void solve() {
  cin >> n >> k;
  for (long long i = 1; i < n + 1; ++i) {
    adjlist[i].clear();
  }
  for (long long i = 0; i < n - 1; ++i) {
    long long u, v, w;
    cin >> u >> v >> w;
    adjlist[u].push_back(make_pair(v, w));
    adjlist[v].push_back(make_pair(u, w));
  }
  dfs(1, 0);
  cout << dp[1][0] << '\n';
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
