思路:判断子树节点个数和k的最小值就好了,long long
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const int N=1e6+10; 5 6 int n,k; 7 vector<pair<int ,ll > > e[N]; 8 ll sum; 9 int a[N]; 10 void dfs(int u,int fa){ 11 a[u]=1; 12 for(int i=0;i<e[u].size();i++){ 13 int v=e[u][i].first; 14 if(v==fa) continue; 15 dfs(v,u); 16 a[u]+=a[v]; 17 } 18 for(int i=0;i<e[u].size();i++){ 19 int v=e[u][i].first; 20 if(v==fa) continue; 21 // cout<<e[u][i].second<<" "<<min(a[u]-1,k)<<" "<<u<<endl; 22 sum+=min(a[v],k)*e[u][i].second; 23 } 24 25 } 26 int main(){ 27 while(scanf("%d%d",&n,&k)!=EOF){ 28 for(int i=1;i<=n;i++) e[i].clear(); 29 memset(a,0,sizeof(a)); 30 int x,y,z; 31 sum=0; 32 for(int i=1;i<n;i++){ 33 scanf("%d%d%d",&x,&y,&z); 34 e[x].push_back(make_pair(y,z)); 35 e[y].push_back(make_pair(x,z)); 36 } 37 dfs(1,0); 38 cout<<sum<<endl; 39 } 40 }