제출 #251725

#제출 시각아이디문제언어결과실행 시간메모리
251725atoizFireworks (APIO16_fireworks)C++14
26 / 100
1 ms384 KiB
/*input
4 6
1 5
2 5
2 8
3 3
3 2
3 3
2 9
4 4
4 3
*/

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

struct Curve : priority_queue<int>
{
	int end_slope;
	long long offset;

	void swap(Curve &rhs)
	{
		priority_queue::swap(rhs);
		std::swap(end_slope, rhs.end_slope);
		std::swap(offset, rhs.offset);
	}

	void init(int x)
	{
		while (!empty()) pop();
		push(x), push(x);
		end_slope = 1;
		offset = 0;
	}

	void merge(Curve &rhs)
	{
		if (size() < rhs.size()) swap(rhs);
		if (rhs.empty()) return;
		if (top() < rhs.top()) offset = offset + rhs.offset + (long long) end_slope * (rhs.top() - top());
		else offset = offset + rhs.offset + (long long) rhs.end_slope * (top() - rhs.top());
		end_slope += rhs.end_slope;
		for (; !rhs.empty(); rhs.pop()) push(rhs.top());
	}

	void normalize(int x)
	{
		for (; end_slope > 1; --end_slope) {
			int t = top();
			pop();
			offset -= (long long) (t - top()) * (end_slope - 1);
		}

		int first = top();
		pop();
		int second = top();
		pop();
		push(second + x);
		push(first + x);
	}
};

int main()
{
	ios_base::sync_with_stdio(0); cin.tie(0);
	int N, M;
	cin >> N >> M;
	vector<int> P(N + M + 1), C(N + M + 1);
	for (int i = 2; i <= N + M; ++i) cin >> P[i] >> C[i];
	vector<Curve> curves(N + M + 1);
	for (int i = N + M; i > N; --i) {
		curves[i].init(C[i]);
		curves[P[i]].merge(curves[i]);
	}
	for (int i = N; i > 1; --i) {
		curves[i].normalize(C[i]);
		curves[P[i]].merge(curves[i]);
	}
	curves[1].normalize(0);
	cout << curves[1].offset << endl;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...