#include <bits/stdc++.h>
using namespace std;
#define int long long
#define sz(x) (int)x.size()
#define all(x) x.begin() , x.end()
const int N = 1e5 + 7;
const int inf = 1e18 + 7;
int n,k;
int ans[N];
vector<pair<int,int>>tree[N];
int heavy[N];
int set_heavy(int node , int par){
int maxi = -1;
for(auto itr : tree[node]){
if(itr.first == par)continue;
int val = set_heavy(itr.first , node) + itr.second;
if(maxi < val){
heavy[node] = itr.first;
maxi = val;
}
}
if(maxi == -1)heavy[node] = -1;
return maxi == -1 ? 0ll : maxi;
}
vector<pair<int , int>>leafs;// path cevabi , node
int mini[N] , maxi[N];
void retrieve(int node , int par , int cumans){
if(heavy[node] == -1){
mini[node] = maxi[node] = sz(leafs);
// cout << "MINI/MAXI " << node+1 << " : " << mini[node] << " " << maxi[node] << endl;
leafs.push_back({cumans , node});
return;
}
mini[node] = -1;
for(auto itr : tree[node]){
if(itr.first == par)continue;
if(heavy[node] == itr.first){
retrieve(itr.first , node , cumans + itr.second);
}
else{
retrieve(itr.first , node , itr.second);
}
if(mini[node] == -1)mini[node] = mini[itr.first];
maxi[node] = maxi[itr.first];
}
// cout << "MINI/MAXI " << node+1 << " : " << mini[node] << " " << maxi[node] << endl;
}
void solve(){
cin >> n >> k;
for(int i = 1;i<n;i++){
int x,y,c;
cin >> x >> y >> c;
x-- , y--;
tree[x].push_back({y , c});
tree[y].push_back({x , c});
}
for(int i = 0;i<n;i++){
leafs.clear();
set_heavy(i , i);
retrieve(i , i , 0ll);
sort(all(leafs));
reverse(all(leafs));
int ans = 0;
for(int j = 0;j<k and j<sz(leafs);j++){
ans += leafs[j].first;
}
cout << ans << '\n';
}
cout << endl;
}
signed main(){
ios_base::sync_with_stdio(0);cin.tie(0);
int testcase=1;//cin >> testcase;
while(testcase--)solve();
cerr << 1000.0 * clock() / CLOCKS_PER_SEC << " ms" << endl;
}
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |
| # | Verdict | Execution time | Memory | Grader output |
|---|
| Fetching results... |