题解:题目给出是一棵树,说明每条边都会用到,而每条边最多能用的次数为min(以该边连接的子节点为根的子树大小,k)
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=1e6+10;
struct edge{
int v,w;
};
int n,cnt,k,fa[maxn],sz[maxn],w[maxn],q[maxn];
ll ans;
bool vis[maxn];
vector<edge> e[maxn];
void bfs(){
q[++cnt]=1;vis[1]=1;
int cur=0;
while(cur<cnt){
int u=q[++cur];
for(int i=0;i<e[u].size();i++){
int v=e[u][i].v;
if(!vis[v]) q[++cnt]=v,fa[v]=u,w[v]=e[u][i].w,vis[v]=1;
}
}
for(int i=cnt;i>0;i--){
int u=q[i];
sz[u]++,sz[fa[u]]+=sz[u];
}
for(int i=1;i<=n;i++) ans+=1ll*min(k,sz[i])*w[i];
}
int main(){
while(scanf("%d%d",&n,&k)!=EOF){
ans=cnt=0;
for(int i=1;i<=n;i++) vis[i]=sz[i]=fa[i]=0,e[i].clear();
for(int u,v,w,i=1;i<n;i++){
scanf("%d%d%d",&u,&v,&w);
e[u].push_back(edge{v,w});
e[v].push_back(edge{u,w});
}
bfs();
printf("%lld\n",ans);
}
}