Submission #1129688

#TimeUsernameProblemLanguageResultExecution timeMemory
1129688sad_hamsterwheePaths (RMI21_paths)C++20
0 / 100
160 ms11900 KiB
#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 = 0; void rem(int v) { if (v == 0) return; auto it = s1.find(v); if (it != s1.end()) { sum -= v; s1.erase(it); } else { s2.erase(s2.find(v)); return; } if (s1.size() < k && !s2.empty()) { int maxv = *s2.rbegin(); s2.erase(s2.find(maxv)); s1.insert(maxv); sum += maxv; } } void add(int v) { if (v == 0) return; s1.insert(v); sum += v; 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 u, int p) { for (int i = 0; i < G[u].size(); i++) { int v = G[u][i].first; int w = G[u][i].second; if (v == p) continue; dfs1(v, u); if (ch[v] + w > ch[u]) { ch[u] = ch[v] + w; son[u] = v; } } for (int i = 0; i < G[u].size(); i++) { int v = G[u][i].first; int w = G[u][i].second; if (v == p || v == son[u]) continue; if (ch[v] + w > ch2[u]) { ch2[u] = ch[v] + w; son2[u] = v; } add(ch[v] + w); } } void dfs2(int u, int p, int pw) { ans[u] = sum; for (int i = 0; i < G[u].size(); i++) { int v = G[u][i].first; int w = G[u][i].second; if (v == p) continue; rem(ch[v] + w); add(ch[v]); int mx; if (v == son[u]) { mx = max(pw, ch2[u]) + w; } else { mx = max(pw, ch[u]) + w; } rem(mx - w); add(mx); dfs2(v, u, 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 x, y, c; cin >> x >> y >> c; G[y].push_back({x, c}); G[x].push_back({y, c}); } 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 timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...