#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pb push_back
#define sz(x) (int)x.size()
#define all(x) begin(x),end(x)
#define lb(x,y) lower_bound(all(x),y)-begin(x)
mt19937 rng;
void solve() {
int N, M; cin >> N >> M;
vector<vector<int>> adj(N);
vector<int> len(N + M, 0);
for (int i = 1; i < N + M; i++) {
int u; cin >> u; u--;
adj[u].pb(i);
cin >> len[i];
}
if (M == 0) {
cout << 0 << "\n";
return;
}
vector<priority_queue<ll>> x(N + M);
vector<ll> y(N + M, 0);
for (int u = N + M - 1; u >= 0; u--) {
if (u >= N) {
x[u].push(len[u]);
x[u].push(len[u]);
} else {
for (int v : adj[u]) {
if (sz(x[v]) > sz(x[u])) {
swap(x[u], x[v]);
swap(y[u], y[v]);
}
}
int slope = 1;
for (int v : adj[u]) {
if (x[v].empty()) continue;
y[u] += y[v] + slope * abs(x[v].top() - x[u].top());
while (!x[v].empty()) {
x[u].push(x[v].top());
x[v].pop();
}
slope++;
}
for (int i = sz(adj[u]) - 1; i >= 1; i--) {
ll n = x[u].top(); x[u].pop();
y[u] -= i * (n - x[u].top());
}
ll n2 = x[u].top(); x[u].pop();
ll n1 = x[u].top(); x[u].pop();
n1 += len[u];
n2 += len[u];
x[u].push(n1);
x[u].push(n2);
}
}
cout << y[0] << "\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
rng = mt19937(chrono::steady_clock::now().time_since_epoch().count());
solve();
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
348 KB |
Output is correct |
2 |
Incorrect |
0 ms |
348 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
1 ms |
348 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
348 KB |
Output is correct |
2 |
Incorrect |
0 ms |
348 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
0 ms |
348 KB |
Output is correct |
2 |
Incorrect |
0 ms |
348 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |