#include <bits/stdc++.h>
using namespace std;
void __print(int x) { cerr << x; }
void __print(long x) { cerr << x; }
void __print(long long x) { cerr << x; }
void __print(unsigned x) { cerr << x; }
void __print(unsigned long x) { cerr << x; }
void __print(unsigned long long x) { cerr << x; }
void __print(float x) { cerr << x; }
void __print(double x) { cerr << x; }
void __print(long double x) { cerr << x; }
void __print(char x) { cerr << '\'' << x << '\''; }
void __print(const char* x) { cerr << '\"' << x << '\"'; }
void __print(const string& x) { cerr << '\"' << x << '\"'; }
void __print(bool x) { cerr << (x ? "true" : "false"); }
template <typename T, typename V>
void __print(const pair<T, V>& x) {
  cerr << '{';
  __print(x.first);
  cerr << ',';
  __print(x.second);
  cerr << '}';
}
template <typename T>
void __print(const T& x) {
  int f = 0;
  cerr << '{';
  for (auto& i : x) cerr << (f++ ? "," : ""), __print(i);
  cerr << "}";
}
void _print() { cerr << "]\n"; }
template <typename T, typename... V>
void _print(T t, V... v) {
  __print(t);
  if (sizeof...(v)) cerr << ", ";
  _print(v...);
}
const int M = 1e9 + 7;
const int N = 5e5 + 10;
vector<pair<int, int>> adj[N];
long long dp[N][2];
int n, k;
void dfs(int i, int p) {
  long long s = 0;
  vector<long long> A;
  for (auto j : adj[i]) {
    if (j.first == p) {
      continue;
    }
    dfs(j.first, i);
    s += dp[j.first][0];
    A.push_back(dp[j.first][1] + j.second - dp[j.first][0]);
  }
  dp[i][0] = s;
  dp[i][1] = s;
  sort(A.begin(), A.end(), greater<long long>());
  for (int j = 0; j < (int)A.size(); ++j) {
    if (A[j] < 0) {
      break;
    }
    if (j <= k - 1) {
      dp[i][0] += A[j];
    }
    if (j <= k - 2) {
      dp[i][1] += A[j];
    }
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    cin >> n >> k;
    for (int i = 0; i < n; ++i) {
      adj[i].clear();
    }
    for (int i = 0; i < n; ++i) {
      dp[i][0] = 0;
      dp[i][1] = 0;
    }
    int u, v, w;
    for (int i = 0; i < n - 1; ++i) {
      cin >> u >> v >> w;
      --u;
      --v;
      adj[u].push_back({v, w});
      adj[v].push_back({u, w});
    }
    dfs(0, -1);
    cout << max(dp[0][0], dp[0][1]) << "\n";
  }
  return 0;
}
