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>
typedef long long ll;
struct V {
int w = 0;
std::vector<int> edges;
ll y0 = 0;
int d0 = 0;
std::priority_queue<int> points;
};
void solve(int i, std::vector<V>& graph) {
V& v = graph[i];
if (v.edges.empty()) return;
for (auto j : v.edges) {
solve(j, graph);
V& w = graph[j];
v.y0 += w.y0;
v.d0 += w.d0;
if (v.points.size() < w.points.size()) {
std::swap(v.points, w.points);
}
while (!w.points.empty()) {
v.points.push(w.points.top());
w.points.pop();
}
}
if (i == 1) return;
v.y0 += v.w;
ll pv1 = v.points.top(); v.points.pop();
ll pv2 = v.points.top(); v.points.pop();
while (v.d0 + (int)v.points.size() > -1) {
pv1 = pv2;
pv2 = v.points.top();
v.points.pop();
}
v.points.push(pv2 + v.w);
v.points.push(pv1 + v.w);
}
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
int n, m;
std::cin >> n >> m;
std::vector<V> graph(n + m + 1);
for (int i = 2; i <= n + m; i++) {
int a, b;
std::cin >> a >> b;
graph[a].edges.push_back(i);
graph[i].w = b;
}
for (int i = n + 1; i <= n + m; i++) {
graph[i].y0 = graph[i].w;
graph[i].d0 = -1;
graph[i].points.push(graph[i].w);
graph[i].points.push(graph[i].w);
}
solve(1, graph);
std::vector<int> points;
while (!graph[1].points.empty()) {
points.push_back(graph[1].points.top());
graph[1].points.pop();
}
std::reverse(points.begin(), points.end());
int x = 0;
ll y = graph[1].y0;
int d = graph[1].d0;
ll min = y;
for (auto p : points) {
y += (ll) d * (p - x);
d++;
x = p;
min = std::min(min, y);
}
std::cout << min << '\n';
return 0;
}
# | 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... |