//Oh? You're Approaching Me?
#include <bits/stdc++.h>
using namespace std;
//
//#define int long long
typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
// #pragma GCC optimize("O3,unroll-loops")
#define migmig ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define pb push_back
#define F first
#define S second
#define SZ(x) ll((x).size())
#define all(x) (x).begin(), (x).end()
#define cl clear
#define endl '\n'
#define deb(x) cerr << #x << " = " << x << '\n'
#define dokme(x) {cout << x << endl; return;}
#define wtf cout << "[ahaaaaaaaaaaaaaaaa]" << endl;
const int maxn = 2e6 + 10;
const int mod = 998244353;
const int inf = 1e9 + 5;
const int LOG = 22;
const int sq = 502;
const int K = 11;
#define mid ((l + r) / 2)
#define lc (id * 2)
#define rc (lc + 1)
//g++ main.cpp -o main && main.exe
int n, m, lf[maxn], C[maxn], sum;
priority_queue<int> pq[maxn];
vector<int> G[maxn];
void dfs(int v) {
if (G[v].empty()) {
pq[v].push(C[v]);
pq[v].push(C[v]);
lf[v] = 1;
return;
}
for (int u : G[v]) {
dfs(u);
if (SZ(pq[u]) > SZ(pq[v]))
swap(pq[v], pq[u]);
while (!pq[u].empty()) {
pq[v].push(pq[u].top());
pq[u].pop();
}
lf[v] += lf[u];
}
int a = -lf[v];
while (a + SZ(pq[v]) > 1) {
pq[v].pop();
}
int x = pq[v].top();
pq[v].pop();
int y = pq[v].top();
pq[v].pop();
pq[v].push(C[v] + x);
pq[v].push(C[v] + y);
}
int vc[maxn];
signed main() {
cin >> n >> m;
C[1] = 0;
for (int i = 2; i <= n + m; i++) {
int p;
cin >> p >> C[i];
G[p].pb(i);
sum += C[i];
}
dfs(1);
int a = -lf[1], i = 1;
while (!pq[1].empty()) {
vc[SZ(pq[1])] = pq[1].top();
pq[1].pop();
}
vc[0] = 0;
while (a < 0) {
sum += a * (vc[i] - vc[i - 1]);
a++;
i++;
}
cout << sum << '\n';
}
| # | 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... |