256182026-02-23 17:21:51GeneratrollRaktárba szállítás (45 pont)cpp17Accepted 45/4514ms4184 KiB
#include <bits/stdc++.h>

using namespace std;

using ll = long long;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int n, k, c;
	cin >> n >> k >> c;
	vector<vector<int>> g(n + 1);
	vector<int> a(n + 1);
	for (int i = 1; i <= n; i++) {
		int p, x;
		cin >> p >> x;
		if (p != 0) {
			g[p].push_back(i);
		}
		a[i] = x;
	}
	vector<multiset<int>> ms(n + 1);
	vector<int> cz(n + 1, 0);
	auto dfs = [&](auto self, int u) -> void {
		for (int v : g[u]) {
			self(self, v);
			if (ms[u].size() < ms[v].size()) {
				ms[u].swap(ms[v]);
				swap(cz[u], cz[v]);
			}
			cz[u] += cz[v];
			for (int e : ms[v]) {
				ms[u].insert(e);
			}
			ms[v].clear();
			if (cz[u] >= k) {
				cz[u] = k;
				ms[u].clear();
			} else {
				while (cz[u] + (int)ms[u].size() > k) {
					ms[u].erase(prev(ms[u].end()));
				}
			}
		}
		int x = a[u];
		while (!ms[u].empty() && *ms[u].begin() == 0) {
			ms[u].erase(ms[u].begin());
			cz[u]++;
		}
		while (x > 0 && !ms[u].empty()) {
			int e = *ms[u].begin();
			ms[u].erase(ms[u].begin());
			if (x >= e) {
				x -= e;
				cz[u]++;
			} else {
				ms[u].insert(e - x);
				x = 0;
			}
		}
		if (x > 0 && cz[u] < k) {
			int num = min((ll)x / c, (ll)k - cz[u] - (int)ms[u].size());
			cz[u] += num;
			x -= num * c;
			if (x > 0 && cz[u] + (int)ms[u].size() < k) {
				ms[u].insert(c - x);
				x = 0;
			}
		}
		if (cz[u] >= k) {
			cz[u] = k;
			ms[u].clear();
		} else {
			while (cz[u] + (int)ms[u].size() > k) {
				ms[u].erase(prev(ms[u].end()));
			}
		}
	};
	dfs(dfs, 1);
	ll r = (ll)cz[1] * c;
	for (int e : ms[1]) {
		r += (c - e);
	}
	cout << r << '\n';
	return 0;
}

SubtaskSumTestVerdictTimeMemory
base45/45
1Accepted0/01ms316 KiB
2Accepted0/07ms1332 KiB
3Accepted1/11ms332 KiB
4Accepted1/11ms316 KiB
5Accepted1/11ms316 KiB
6Accepted1/11ms316 KiB
7Accepted1/11ms316 KiB
8Accepted1/11ms316 KiB
9Accepted1/16ms1224 KiB
10Accepted1/16ms1348 KiB
11Accepted1/14ms1332 KiB
12Accepted1/11ms316 KiB
13Accepted1/11ms316 KiB
14Accepted1/11ms316 KiB
15Accepted1/11ms456 KiB
16Accepted1/11ms316 KiB
17Accepted1/11ms380 KiB
18Accepted1/11ms500 KiB
19Accepted1/12ms316 KiB
20Accepted1/12ms456 KiB
21Accepted2/27ms1332 KiB
22Accepted2/27ms1376 KiB
23Accepted2/27ms1236 KiB
24Accepted3/314ms2356 KiB
25Accepted3/314ms2356 KiB
26Accepted3/37ms2356 KiB
27Accepted3/36ms2356 KiB
28Accepted3/310ms4148 KiB
29Accepted3/312ms4176 KiB
30Accepted3/312ms4184 KiB