Submission #1129701

#TimeUsernameProblemLanguageResultExecution timeMemory
1129701sad_hamsterwheePaths (RMI21_paths)C++17
100 / 100
260 ms17288 KiB
#include <bits/stdc++.h> #define int long long using namespace std; const int maxn = 1e5 + 10; int ch[maxn], son[maxn], ch2[maxn], son2[maxn], n, k; multiset<int> s1, s2; int sum; void add(int u) { if (u == 0) return; s1.insert(u); sum += u; if (s1.size() > k) { int minv = (*s1.begin()); sum -= minv; s1.erase(s1.find(minv)); s2.insert(minv); } } void rem(int u) { if (u == 0) return; if (s1.find(u) != s1.end()) { sum -= u; s1.erase(s1.find(u)); } else { s2.erase(s2.find(u)); return; } if (s1.size() < k && s2.size() > 0) { int maxv = (*s2.rbegin()); s2.erase(s2.find(maxv)); s1.insert(maxv); sum += maxv; } } vector<pair<int, int>> G[maxn]; int ans[maxn]; void dfs1(int u, int fa) { for (pair<int, int> nxt : G[u]) { int v = nxt.first, w = nxt.second; if (v == fa) continue; dfs1(v, u); if (ch[v] + w > ch[u]) { son[u] = v; ch[u] = ch[v] + w; } } for (pair<int, int> nxt : G[u]) { int v = nxt.first, w = nxt.second; if (v == fa || v == son[u]) continue; if (ch[v] + w > ch2[u]) { son2[u] = v; ch2[u] = ch[v] + w; } add(ch[v] + w); } } void dfs2(int u, int fa, int weif) { ans[u] = sum; for (pair<int, int> nxt : G[u]) { int v = nxt.first, w = nxt.second; if (v == fa) continue; rem(ch[v] + w); add(ch[v]); int mx; if (v == son[u]) { mx = max(weif, ch2[u]) + w; } else { mx = max(weif, 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 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 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...