#include<bits/stdc++.h>
#define pb push_back
#define x first
#define y second
#define all(a) (a).begin(), (a).end()
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
const int maxn = 3e5 + 5;
struct Data {
int idx;
ll lo, hi, ans;
};
int n, m;
ll w[maxn];
ll depth[maxn];
Data dp[maxn];
vector<pair<int, ll>> adj[maxn];
void dfs(int x) {
for(auto p : adj[x])
depth[p.x] = p.y + depth[x], w[p.x] = p.y, dfs(p.x);
}
Data solve(int x) {
if(adj[x].size() == 0)
return dp[x] = {x, depth[x], depth[x], 0};
ll sum = 0;
vector<Data> ch;
for(auto p : adj[x])
ch.pb(solve(p.x)), sum += ch.back().ans;
set<ll> vals;
for(Data D : ch)
vals.insert(D.lo), vals.insert(D.hi);
vector<ll> v;
ll ans = 1e8;
for(ll val : vals) {
ll sol = 0;
for(Data D : ch) {
if(D.lo <= val && val <= D.hi) continue;
if(val > D.hi) sol += val - D.hi;
else {
if(D.lo - val > w[D.idx]) {sol = 1e18;break;}
else sol += D.lo - val;
}
}
if(sol < ans) v.clear(), ans = sol;
if(sol == ans) v.pb(val);
}
Data ret;
ret.idx = x;
ret.ans = ans + sum;
ret.lo = v[0];
ret.hi = v.back();
//cout << x + 1 << " -> " << ret.lo << " " << ret.hi << " " << ret.ans << "\n";
return dp[x] = ret;
}
int main() {
scanf("%d%d", &n, &m);
for(int i = 1;i < n + m;i++) {
int p, c;
scanf("%d%d", &p, &c);
p--;
adj[p].pb({i, c});
}
dfs(0);
Data ans = solve(0);
printf("%lld\n", ans.ans);
return 0;
}
Compilation message
fireworks.cpp: In function 'int main()':
fireworks.cpp:70:7: warning: ignoring return value of 'int scanf(const char*, ...)' declared with attribute 'warn_unused_result' [-Wunused-result]
70 | scanf("%d%d", &n, &m);
| ~~~~~^~~~~~~~~~~~~~~~
fireworks.cpp:73:8: warning: ignoring return value of 'int scanf(const char*, ...)' declared with attribute 'warn_unused_result' [-Wunused-result]
73 | scanf("%d%d", &p, &c);
| ~~~~~^~~~~~~~~~~~~~~~
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
4 ms |
7252 KB |
Output is correct |
2 |
Runtime error |
12 ms |
14656 KB |
Execution killed with signal 11 |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
4 ms |
7380 KB |
Output is correct |
2 |
Correct |
4 ms |
7380 KB |
Output is correct |
3 |
Incorrect |
3 ms |
7356 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
4 ms |
7252 KB |
Output is correct |
2 |
Runtime error |
12 ms |
14656 KB |
Execution killed with signal 11 |
3 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
4 ms |
7252 KB |
Output is correct |
2 |
Runtime error |
12 ms |
14656 KB |
Execution killed with signal 11 |
3 |
Halted |
0 ms |
0 KB |
- |