#include <string>
#include <iostream>
#include <queue>
#include <math.h>
#include <stack>
#include <map>
#include <algorithm>
#include <set>
#include <tuple>
#include <stack>
#include <vector>
#include <sstream>
#include <deque>
#include <string>
#include <cstring>
#include <cmath>
#include <numeric>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 5;
int ch[maxn], son[maxn], ch2[maxn], son2[maxn], n, k;
multiset<int> s1, s2;
int sum;
void rem(int i) {
if (i == 0) return;
if (s1.find(i) != s1.end()) {
sum -= i;
s1.erase(s1.find(i));
} else {
s2.erase(s2.find(i));
return;
}
if (s1.size() < k && s2.size() > 0) {
int maxv = (*s2.rbegin());
s2.erase(s2.find(maxv));
s1.insert(maxv);
sum += maxv;
}
}
void add(int i) {
if (i == 0) return;
s1.insert(i);
sum += i;
if (s1.size() > k) {
int minv = (*s1.begin());
sum -= minv;
s1.erase(s1.find(minv));
s2.insert(minv);
}
}
vector<pair<int, int>> G[maxn];
int ans[maxn];
void dfs1(int i, int fa) {
for (pair<int, int> nxt : G[i]) {
int v = nxt.first, w = nxt.second;
if (v == fa) continue;
dfs1(v, i);
if (ch[v] + w > ch[i]) {
son[i] = v;
ch[i] = ch[v] + w;
}
}
for (pair<int, int> nxt : G[i]) {
int v = nxt.first, w = nxt.second;
if (v == fa || v == son[i]) continue;
if (ch[v] + w > ch2[i]) {
son2[i] = v;
ch2[i] = ch[v] + w;
}
add(ch[v] + w);
}
}
void dfs2(int i, int fa, int wfa) {
ans[i] = sum;
for (pair<int, int> nxt : G[i]) {
int v = nxt.first;
int w = nxt.second;
if (v == fa) continue;
rem(ch[v] + w);
add(ch[v]);
int mx = (v == son[i]) ? max(wfa, ch2[i]) + w : max(wfa, ch[i]) + w;
rem(mx - w);
add(mx);
dfs2(v, i, mx);
rem(mx);
add(mx - w);
rem(ch[v]);
add(ch[v] + w);
}
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> k;
for (int i = 1; i < n; i++) {
int u, v, w;
cin >> u >> v >> w;
G[u].push_back(make_pair(v, w));
G[v].push_back(make_pair(u, w));
}
dfs1(1, 0);
add(ch[1]);
dfs2(1, 0, 0);
for (int i = 1; i <= n; i++) {
cout << ans[i] << '\n';
}
return 0;
}
# | 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... |