#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("Ofast")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
typedef long long ll;
#define int ll
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define pb push_back
#define all(x) x.begin(), x.end()
#define sz(x) (int)x.size()
#define mispertion ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define F first
#define S second
#define getlast(s) (*s.rbegin())
#define debg cout << "OK\n"
const ld PI = 3.1415926535;
const int N = 5e5 + 10;
const int M = 1e5 + 10;
int mod = 1e9+7;
const int infi = INT_MAX;
const ll infl = 2e18;
const int P = 505319;
const ld eps = 1e-9;
int mult(int a, int b){
return a * 1LL * b % mod;
}
int sum(int a, int b){
a %= mod;
b %= mod;
if(a + b >= mod)
return a + b - mod;
if(a + b < 0)
return a + b + mod;
return a + b;
}
int binpow(int a, int n){
if (n == 0)
return 1;
if (n % 2 == 1){
return mult(binpow(a, n - 1), a);
}
else{
auto b = binpow(a, n / 2);
return mult(b, b);
}
}
int n, m, h[N];
multiset<int> sl[N];
vector<pii> g[N];
void dfs(int v, int w){
if(v > n){
h[v] = 0;
sl[v].insert(w);
sl[v].insert(w);
return;
}
for(auto ee : g[v]){
int u = ee.F, w = ee.S;
dfs(u, w);
if(sz(sl[u]) > sz(sl[v])){
sl[v].swap(sl[u]);
swap(h[v], h[u]);
}
h[v] += h[u];
if(sz(sl[u]) > 1){
int r1 = *sl[v].rbegin(), l1 = (*(++sl[v].rbegin()));
int r2 = *sl[u].rbegin(), l2 = (*(++sl[u].rbegin()));
if(r1 < l2)
h[v] += (l2 - r1);
else if(r2 < l1)
h[v] += (l1 - r2);
}
for(auto e : sl[u])
sl[v].insert(e);
if(sz(sl[u]) != 0)
sl[v].erase(sl[v].find(*sl[v].rbegin()));
}
int a = *sl[v].rbegin();
int b = *(++sl[v].rbegin());
sl[v].erase(sl[v].find(a));
sl[v].erase(sl[v].find(b));
sl[v].insert(a + w);
sl[v].insert(b + w);
}
void solve(){
cin >> n >> m;
for(int i = 2; i <= n + m; i++){
int p, w;
cin >> p >> w;
g[p].pb({i, w});
}
dfs(1, 0);
cout << h[1] << '\n';
}
signed main(){
mispertion;
int t = 1;
//cin >> t;
while (t--){
solve();
}
return 0;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
14 ms |
35672 KB |
Output is correct |
2 |
Incorrect |
15 ms |
35928 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
21 ms |
35676 KB |
Output is correct |
2 |
Correct |
15 ms |
35672 KB |
Output is correct |
3 |
Incorrect |
15 ms |
35676 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
14 ms |
35672 KB |
Output is correct |
2 |
Incorrect |
15 ms |
35928 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
14 ms |
35672 KB |
Output is correct |
2 |
Incorrect |
15 ms |
35928 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |