#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > tree[500005];
int n, k;
pair<long long, long long> dfs(int u, int p) {
  vector<int> res;
  long long sum = 0;
  for (auto v : tree[u]) {
    if (v.first == p) continue;
    pair<long long, long long> z = dfs(v.first, u);
    sum += z.second;
    res.push_back(z.first + v.second - z.second);
  }
  long long mx1 = sum;
  long long mx2 = sum;
  sort(res.rbegin(), res.rend());
  for (int i = 0; i < res.size(); i++) {
    sum += res[i];
    if (i <= k - 2) {
      mx1 = max(mx1, sum);
    }
    if (i <= k - 1) {
      mx2 = max(mx2, sum);
    }
  }
  return {mx1, mx2};
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    scanf("%d %d", &n, &k);
    for (int i = 0; i <= n; i++) tree[i].clear();
    for (int i = 0; i < n - 1; i++) {
      int u, v, w;
      scanf("%d %d %d", &u, &v, &w);
      tree[u].push_back({v, w});
      tree[v].push_back({u, w});
    }
    pair<long long, long long> z = dfs(1, 0);
    printf("%lld\n", max(z.first, z.second));
  }
  return 0;
}
