Submission #1341703

#TimeUsernameProblemLanguageResultExecution timeMemory
1341703MateiKing80Fireworks (APIO16_fireworks)C++20
100 / 100
268 ms73204 KiB
#include <bits/stdc++.h>

using namespace std;

using ll = long long;
#define int ll

const int N = 300005;
int c[N], sz[N];
vector<int> fii[N];

struct Ura {
	priority_queue<int> points;
	int a, b;
} vura[N];

void join(Ura &a, Ura &b) {
	a.a += b.a;
	a.b += b.b;
	while (!b.points.empty()) {
		a.points.push(b.points.top());
		b.points.pop();
	}
}

void baga(Ura &a, int c) {
	while (a.a > 1) {
		a.a --;
		a.b += a.points.top();
		a.points.pop();
	}
	int x = a.points.top(); a.points.pop();
	int y = a.points.top(); a.points.pop();
	a.points.push(y + c);
	a.points.push(x + c);
	a.b -= c;
}

void dfs(int nod) {
	sz[nod] = 1;
	int fmax = 0;
	for (auto i : fii[nod]) {
		dfs(i);
		sz[nod] += sz[i];
		if (sz[fmax] < sz[i]) {
			fmax = i;
		}
	}
	if (fmax == 0) {
		vura[nod].points.push(c[nod]);
		vura[nod].points.push(c[nod]);
		vura[nod].a = 1;
		vura[nod].b = -c[nod];
		return;
	}
	swap(vura[fmax], vura[nod]);
	for (auto i : fii[nod]) {
		if (i != fmax) {
			join(vura[nod], vura[i]);
		}
	}
	baga(vura[nod], c[nod]);
}

signed main() {
	int n, m;
	cin >> n >> m;
	for (int i = 2; i <= n + m; i ++) {
		int p;
		cin >> p >> c[i];
		fii[p].push_back(i);
	}
	c[1] = 1;
	dfs(1);
	auto a = vura[1];
	while (a.a > 0) {
		a.a --;
		a.b += a.points.top();
		a.points.pop();
	}
	cout << a.b << '\n';
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...