http://codeforces.com/contest/1241/problem/E
#include <bits/stdc++.h>
//#include <queue>
//#include <cmath>
//#include <iostream>
//#include <unordered_map>
#define lson rt<<1
#define rson rt<<1|1
#define lowbit(x) ((x)&(-x))
#define mem(x,y) memset(x,y,sizeof(x))
#define pb push_back
#define INF 0x3f3f3f3f
#define ll long long
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
const int mod=1e9+7;
const int N=5e5+9;
vector<pair<int,ll> >g[N];
ll dp[N][2];
int n,k;
void dfs(int u,int fa)
{
dp[u][1]=dp[u][0]=0;
ll sum=0;
vector<ll>vec;
for(int i=0;i<g[u].size();i++)
{
int v=g[u][i].first;
ll w=g[u][i].second;
if(v==fa) continue;
dfs(v,u);
sum+=dp[v][0];
vec.pb(dp[v][1]+w-dp[v][0]);
}
sort(vec.begin(),vec.end(),greater<int>());
for(int i=0;i<min(k,(int)vec.size());i++)
{
if(vec[i]>0)
sum+=vec[i];
}
dp[u][0]=dp[u][1]=sum;
if(vec.size()>=k) if(vec[k-1]>0) dp[u][1]-=vec[k-1];
}
int main()
{
FAST_IO;
int q;
cin>>q;
while(q--)
{
cin>>n>>k;
for(int i=0;i<=n;i++) g[i].clear();
for(int i=0;i<n-1;i++)
{
int u,v;
ll w;
cin>>u>>v>>w;
g[u].pb({v,w});
g[v].pb({u,w});
}
dfs(1,0);
cout<<max(dp[1][1],dp[1][0])<<endl;
}
return 0;
}