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;
#define int ll
#define endl '\n' //comment for interactive
#define fast_io ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define pb push_back
#define re resize
#define ff first
#define ss second
#define all(x) (x).begin(), (x).end()
#define all1(x) (x).begin()+1, (x).end()
#define loop(i, n) for(int i = 0; i < n; i++)
#define loop1(i, n) for(int i = 1; i <= n; i++)
#define print(x) cout << #x << ": " << x << endl << flush
typedef long long ll;
typedef vector<int> vi;
typedef array<int, 2> ii;
typedef array<int, 3> ti;
typedef vector<ii> vii;
typedef vector<ti> vti;
typedef vector<vi> vvi;
typedef priority_queue<int> pq;
template<class T> bool ckmin(T&a, T b) { bool B = a > b; a = min(a, b); return B; }
template<class T> bool ckmax(T&a, T b) { bool B = a < b; a = max(a, b); return B; }
const int inf = 1e17;
const int maxn = 3e5 + 5;
int p[maxn];
int c[maxn];
vi adj[maxn];
struct slp {
priority_queue<int> pq;
int m = 0, c = 0;
};
slp dfs(int u) {
slp slp1;
for(auto v : adj[u]) {
slp slp2 = dfs(v);
if(slp1.pq.size() < slp2.pq.size()) swap(slp1, slp2);
slp1.m += slp2.m;
slp1.c += slp2.c;
while(!slp2.pq.empty()) {
int x = slp2.pq.top();
slp2.pq.pop();
slp1.pq.push(x);
}
}
if(adj[u].size() == 0) {
slp1.m = -1;
slp1.c = c[u];
slp1.pq.push(c[u]);
slp1.pq.push(c[u]);
return slp1;
}
int x = slp1.m + slp1.pq.size();
loop(i, x-1)
slp1.pq.pop();
slp1.c += c[u];
int a = slp1.pq.top();
slp1.pq.pop();
int b = slp1.pq.top();
slp1.pq.pop();
slp1.pq.push(a + c[u]);
slp1.pq.push(b + c[u]);
return slp1;
}
void solve() {
int n, m;
cin >> n >> m;
loop1(i, n+m) if(i != 1) {
cin >> p[i] >> c[i];
adj[p[i]].pb(i);
}
slp res = dfs(1);
int mr = res.m;
int cr = res.c;
vi pos;
while(!res.pq.empty()) {
pos.pb(res.pq.top());
res.pq.pop();
}
pos.pb(0);
reverse(all(pos));
int ans = cr;
for(int i = 0; i < -mr; i++) {
ans += (mr + i) * (pos[i+1] - pos[i]);
}
cout << ans << endl;
}
signed main() {
fast_io;
int t = 1; //cin >> t;
while(t--)
solve();
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... |