#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> conns;
vector<vector<int>> costs;
size_t n, k;
pair<long long, long long> dfs(int pos, int par) {
  vector<pair<long long, long long>> vec;
  for (size_t i = 0; i < conns[pos].size(); i++) {
    if (conns[pos][i] == par) continue;
    auto p = dfs(conns[pos][i], pos);
    vec.emplace_back(max(0ll, costs[pos][i] + p.second - p.first), p.first);
  }
  sort(vec.rbegin(), vec.rend());
  long long res = 0;
  for (int i = 0; i < min(vec.size(), k - 1); i++) {
    res += vec[i].first + vec[i].second;
  }
  if (vec.size() <= k - 1) return {res, res};
  for (size_t i = k; i < vec.size(); i++) {
    res += vec[i].second;
  }
  return {res + vec[k - 1].first + vec[k - 1].second, res + vec[k - 1].second};
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int N;
  cin >> N;
  for (int i = 0; i < N; i++) {
    cin >> n >> k;
    costs.assign(n, vector<int>(0));
    conns.assign(n, vector<int>(0));
    for (int i = 0; i < n - 1; i++) {
      int a, b, c;
      cin >> a >> b >> c;
      a--;
      b--;
      conns[a].push_back(b);
      conns[b].push_back(a);
      costs[a].push_back(c);
      costs[b].push_back(c);
    }
    cout << dfs(0, 0).first << "\n";
  }
}
