#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<cstdlib>
#define N 100005
#define mod 998244353
#define ll long long
using namespace std;
int T,n,k,u,v,w,tot,head[N*4],size[N],vis[N],dist[N];
ll ans,fac[N],inv[N];
struct node
{
int vet,next,len,u;
}edge[N*4];
void add(int u,int v,int w)
{
edge[++tot].vet=v;
edge[tot].next=head[u];
head[u]=tot;
edge[tot].len=w;
edge[tot].u=u;
}
void dfs(int u,int dis)
{
size[u]=1;
vis[u]=false;
dist[u]=dis;
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].vet;
if(vis[v])
{
dfs(v,dis+1);
size[u]+=size[v];
}
}
}
ll pow(ll a,int b)
{
ll ans=1,p=a;
while(b)
{
if(b%2==1)ans=(ans*p)%mod;
p=(p*p)%mod;
b/=2;
}
return ans;
}
ll calc(int n,int m)
{
if(m>n)return 0;
return ((fac[n]*inv[n-m])%mod*inv[m])%mod;
}
int main()
{
freopen("blink.in","r",stdin);
freopen("blink.out","w",stdout);
fac[0]=1;inv[0]=1;
for(int i=1;i<=N;i++)fac[i]=(fac[i-1]*i)%mod;
for(int i=1;i<=N;i++)inv[i]=pow(fac[i],mod-2);
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&k);
ans=0;tot=0;
memset(head,-1,sizeof(head));
for(int i=1;i<n;i++)
{
scanf("%d%d%d",&u,&v,&w);
add(u,v,w);add(v,u,w);
ans=(ans+w*2)%mod;
}
if(n==k)
{
printf("%d\n",ans);
continue;
}
memset(vis,true,sizeof(vis));
dfs(1,0);
ans=0;
for(int u=1;u<=n;u++)
{
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].vet,u1=u;
if(dist[u1]<dist[v])swap(u1,v);
ans=(ans+(((calc(n,k)-calc(size[u1],k)-calc((n-size[u1]),k))%mod+mod)%mod)*edge[i].len)%mod;
}
}
ll p=calc(n,k);
printf("%lld\n",(ans*pow(p,mod-2))%mod);
}
return 0;
}
闪烁魔法(blink)
最新推荐文章于 2024-07-09 23:29:46 发布