Submission #486538

#TimeUsernameProblemLanguageResultExecution timeMemory
486538SamboorFireworks (APIO16_fireworks)C++17
100 / 100
267 ms83852 KiB
// Grzegorz Ryn
// V LO Kraków

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
#define pb push_back
#define st first
#define nd second

const ll INF = 1'000'000'000;

int N, M;

vector<vector<int>> g;
vector<ll> cost;

vector<int> slope_ind;
vector<priority_queue<ll>> slope;
vector<ll> initial_slope, final_slope, first_value;

void dfs(int v) {
	if(v > N) {
		slope[v].push(cost[v]);
		slope[v].push(cost[v]);
		initial_slope[v] = -1;
		final_slope[v] = 1;
		first_value[v] = cost[v];
		return;
	}
	
	for(int u:g[v]) {
		dfs(u);
		
		int V = slope_ind[v];
		int U = slope_ind[u];
		if(slope[V].size() < slope[U].size()) {
			swap(V, U);
			swap(slope_ind[v], slope_ind[u]);
		}
		while(slope[U].size() > 0) {
			slope[V].push(slope[U].top());
			slope[U].pop();
		}
		
		first_value[v] += first_value[u];
		initial_slope[v] += initial_slope[u];
		final_slope[v] += final_slope[u];
	}
	
	ll V = slope_ind[v], l, r;
	while(final_slope[v] >= 0) {
		if(final_slope[v] == 1) {
			r = slope[V].top();
		}
		else if(final_slope[v] == 0) {
			l = slope[V].top();
		}
		
		slope[V].pop();
		final_slope[v]--;
	}
	
	first_value[v] += cost[v];
	slope[V].push(l + cost[v]);
	slope[V].push(r + cost[v]);
	final_slope[v] = 1;
}

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	
	cin >> N >> M;
	
	g.resize(N+M+1);
	cost.resize(N+M+1, 0);
	
	slope.resize(N+M+1);
	slope_ind.resize(N+M+1);
	iota(slope_ind.begin(), slope_ind.end(), 0);
	initial_slope.resize(N+M+1, 0);
	final_slope.resize(N+M+1, 0);
	first_value.resize(N+M+1, 0);
	
	for(int i=2; i<=N+M; i++) {
		int p;
		cin >> p >> cost[i];
		g[p].pb(i);
	}

	dfs(1);
	
	int it = slope_ind[1];
	ll result = (ll)INF*INF, res = first_value[1], prv = 0;
	vector<ll> pos;
	while(slope[it].size() > 0) {
		pos.pb(slope[it].top());
		slope[it].pop();
	}
	reverse(pos.begin(), pos.end());
	
	for(ll p : pos) {
		res += initial_slope[1] * (p - prv);
		initial_slope[1]++;
		prv = p;
		result = min(result, res);
		
		if(initial_slope[1] >= 0) {  
			break;
		}
	}
	
	cout << result << '\n';

	return 0;
}

Compilation message (stderr)

fireworks.cpp: In function 'void dfs(int)':
fireworks.cpp:68:18: warning: 'r' may be used uninitialized in this function [-Wmaybe-uninitialized]
   68 |  slope[V].push(r + cost[v]);
fireworks.cpp:67:18: warning: 'l' may be used uninitialized in this function [-Wmaybe-uninitialized]
   67 |  slope[V].push(l + cost[v]);
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...