제출 #1129692

#제출 시각아이디문제언어결과실행 시간메모리
1129692sad_hamsterwheePaths (RMI21_paths)C++17
0 / 100
163 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;

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);
    }
}

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;
    }
}

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 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...