154452025-02-19 16:27:13feheristvanTársaság (50)cpp17Wrong answer 7/5010ms1332 KiB
#include <iostream>
#include <bits/stdc++.h>

using namespace std;

struct elem {
    int node, weight; // Store both the node and the communication time
    elem* kov;
};

// Function to insert an edge into the adjacency list
void beszur(elem* first, int x, int w) {
    elem* p = new elem;
    p->node = x;
    p->weight = w;
    p->kov = first->kov;
    first->kov = p;
}

const int INF = 1e9;
int N, K;
elem* first[10001];  // Adjacency list using linked lists
vector<int> maxDist; // Store max distances from the root (1)

void dfs(int node, int parent, int dist) {
    maxDist[node] = dist;
    for (elem* e = first[node]->kov; e != nullptr; e = e->kov) {
        if (e->node != parent) {
            dfs(e->node, node, dist + e->weight);
        }
    }
}

// Check if we can achieve a max waiting time of `maxTime` with `K` selected nodes
bool canAchieve(int maxTime) {
    vector<int> candidates;

    for (int i = 2; i <= N; i++) {
        if (first[i]->kov == nullptr) { // If it's a leaf node
            candidates.push_back(maxDist[i]);
        }
    }

    sort(candidates.rbegin(), candidates.rend()); // Sort descending

    if (candidates.size() <= K) return true; // If we can select all, it's valid

    return candidates[K] <= maxTime;
}

// Binary search to find the minimum max waiting time
int binarySearch() {
    int lo = 0, hi = INF, ans = INF;
    
    while (lo <= hi) {
        int mid = (lo + hi) / 2;
        if (canAchieve(mid)) {
            ans = mid;
            hi = mid - 1;
        } else {
            lo = mid + 1;
        }
    }
    
    return ans;
}

int main() {
    cin >> N >> K;
    for (int i = 1; i <= N; i++) {
        first[i] = new elem;
        first[i]->kov = nullptr;
    }

    int x, y, t;
    for (int i = 2; i <= N; i++) {
        cin >> x >> t;
        beszur(first[x], i, t);
        beszur(first[i], x, t);
    }

    maxDist.resize(N + 1, 0);
    dfs(1, -1, 0);

    cout << binarySearch() << endl;

    return 0;
}
SubtaskSumTestVerdictTimeMemory
base7/50
1Wrong answer0/01ms500 KiB
2Wrong answer0/06ms820 KiB
3Wrong answer0/31ms316 KiB
4Wrong answer0/31ms316 KiB
5Accepted3/31ms316 KiB
6Wrong answer0/31ms316 KiB
7Wrong answer0/31ms432 KiB
8Wrong answer0/32ms500 KiB
9Wrong answer0/33ms564 KiB
10Wrong answer0/34ms564 KiB
11Wrong answer0/34ms820 KiB
12Wrong answer0/36ms820 KiB
13Wrong answer0/47ms984 KiB
14Wrong answer0/48ms1044 KiB
15Wrong answer0/49ms1264 KiB
16Accepted4/49ms1204 KiB
17Wrong answer0/410ms1332 KiB