# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
636778 | lovrot | Fireworks (APIO16_fireworks) | C++11 | 0 ms | 0 KiB |
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>
#define ll long long
#define X first
#define Y second
#define pii pair<int, int>
#define pb push_back
using namespace std;
const int N = 310;
const ll INF = 1e9;
ll abs2(ll x){
return x < 0 ? -x : x;
}
int n, m;
ll dp[N][N], c[N], p[N], calc[N];
ll maxi, dist;
vector<int> g[N];
ll DP(int u, ll d){
if(d < 0 || d > maxi) return INF;
if(g[u].size() == 0){
if(d > dist) return INF;
return abs2(dist - (d + c[u]));
}
if(dp[u][d] != -1) return dp[u][d];
dp[u][d] = INF;
for(ll dx = 0; dx <= dista; dx++){
ll res = abs2(c[u] - dx);
for(int v : g[u]){
res += DP(v, d + dx);
}
dp[u][d] = min(dp[u][d], res);
}
return dp[u][d];
}
int main(){
ios_base::sync_with_stdio(false);
scanf("%d%d", &n, &m);
for(int i = 2; i <= n + m; i++){
scanf("%d%d", &p[i], &c[i]);
g[p[i]].pb(i);
calc[i] = calc[p[i]] + c[i];
maxi = max(maxi, calc[i]);
}
ll ans = INF;
for(dist; dist <= maxi; dist++){
memset(dp, -1, sizeof(dp));
DP(1, 0);
ans = min(ans, dp[1][0]);
}
printf("%d", ans);
return 0;
}