8682022-01-21 20:49:05Valaki2Társaság (50)cpp14Accepted 50/5014ms3972 KiB
#include <bits/stdc++.h>
using namespace std;

#define int long long
#define pb push_back
#define mp make_pair
#define fi first
#define se second

struct edge {
    int to;
    int weight;
    edge() : to(0), weight(0) {}
    edge(int to_, int weight_) : to(to_), weight(weight_) {}
};

struct node {
    edge parent;
    vector<edge> children;
    node() {
        parent = edge();
        children.assign(0, edge());
    }
};

int n, k;
vector<node> v;

int dfs(int cur, int &cnt, int &max_sum) {
    int max_dist = 0;
    for(edge nei : v[cur].children) {
        int cur_dist = dfs(nei.to, cnt, max_sum);
        max_dist = max(cur_dist, max_dist);
    }
    max_dist += v[cur].parent.weight;
    if(max_dist > max_sum) {
        cnt++;
        return 0;
    } else {
        return max_dist;
    }
}

bool ok(int max_sum) {
    int cnt = 0;
    for(edge nei : v[1].children) {
        dfs(nei.to, cnt, max_sum);
    }
    return cnt <= k;
}

void solve() {
    cin >> n >> k;
    v.assign(1 + n, node());
    int weight_sum = 0;
    for(int i = 2; i <= n; i++) {
        int j, w;
        cin >> j >> w;
        v[i].parent = edge(j, w);
        v[j].children.pb(edge(i, w));
        weight_sum += w;
    }
    int l = -1, r = weight_sum;
    while(l < r - 1) {
        int mid = (l + r) / 2;
        if(ok(mid)) {
            r = mid;
        } else {
            l = mid;
        }
    }
    cout << r << "\n";
}

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    solve();
    return 0;
}
SubtaskSumTestVerdictTimeMemory
base50/50
1Accepted0/02ms1820 KiB
2Accepted0/07ms2392 KiB
3Accepted3/31ms1980 KiB
4Accepted3/31ms1988 KiB
5Accepted3/31ms1996 KiB
6Accepted3/31ms2008 KiB
7Accepted3/32ms2028 KiB
8Accepted3/33ms2068 KiB
9Accepted3/34ms2284 KiB
10Accepted3/34ms2364 KiB
11Accepted3/34ms2436 KiB
12Accepted3/38ms2632 KiB
13Accepted4/48ms2900 KiB
14Accepted4/413ms3116 KiB
15Accepted4/414ms3340 KiB
16Accepted4/412ms3452 KiB
17Accepted4/414ms3972 KiB