This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
const int N = 300005;
struct Node {
long long startingValue;
long long startingSlope;
priority_queue<long long> pq;
};
int n, m, c[N], p[N];
vector<int> G[N];
Node a[N];
void dfs(int u) {
if (u > n) return;
int mx = 0;
for (auto v : G[u]) {
dfs(v);
if (!mx || a[v].pq.size() > a[mx].pq.size()) mx = v;
}
swap(a[mx], a[u]);
for (auto v : G[u]) {
if (v == mx) continue;
while (a[v].pq.size()) {
a[u].pq.push(a[v].pq.top()), a[v].pq.pop();
}
a[u].startingValue += a[v].startingValue;
a[u].startingSlope += a[v].startingSlope;
}
while (a[u].startingSlope + a[u].pq.size() > 1) a[u].pq.pop();
long long x1 = a[u].pq.top(); a[u].pq.pop();
long long x0 = a[u].pq.top(); a[u].pq.pop();
a[u].startingValue += c[u];
a[u].pq.push(x0 + c[u]), a[u].pq.push(x1 + c[u]);
}
int main() {
ios::sync_with_stdio(false);
cin >> n >> m;
for (int i = 2; i <= n + m; ++i) {
cin >> p[i] >> c[i];
G[p[i]].push_back(i);
}
for (int i = n + 1; i <= n + m; ++i) {
a[i].startingSlope = -1;
a[i].startingValue = c[i];
a[i].pq.push(c[i]), a[i].pq.push(c[i]);
}
dfs(1);
vector<long long> v;
while (a[1].pq.size()) {
v.push_back(a[1].pq.top()), a[1].pq.pop();
}
reverse(v.begin(), v.end());
long long cur = 0;
long long curSlope = a[1].startingSlope;
long long res = a[1].startingValue;
// cout << curSlope << ' ' << res << '\n';
// for (auto i : v) cout << i << ' '; cout << '\n';
for (int i = 0; i < v.size(); ++i) {
res += (v[i] - cur) * curSlope, curSlope++, cur = v[i];
}
cout << res;
}
Compilation message (stderr)
fireworks.cpp: In function 'int main()':
fireworks.cpp:62:20: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
for (int i = 0; i < v.size(); ++i) {
^
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |