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;
typedef long long ll;
const int MAXN = 505;
int n, m, L[MAXN], R[MAXN];
vector<pair<int, int> > adj[MAXN];
ll walk[MAXN], dp[MAXN][MAXN];
void precalc(int node){
	for(pair<int, int> x : adj[node]){
		walk[x.first] = walk[node] + x.second;
		precalc(x.first);
	}
}
void dfs(int node){
	if(node >= n){
		for(int i = 0; i < MAXN; ++i) dp[node][i] = 1e9;
		dp[node][walk[node]] = 0;
	}
	for(pair<int, int> x : adj[node]){
		dfs(x.first);
		for(int i = 0; i < MAXN; ++i){
			ll mini = 1e9;
			for(int j = 0; j < MAXN; ++j){
				if(x.second + i - j >= 0) mini = min(mini, dp[x.first][j] + abs(i - j));
			}
			dp[node][i] += mini;
		}
	}
}
int main(){
	cin >> n >> m;
	for(int i = 1; i < n + m; ++i){
		int p, c;
		cin >> p >> c, --p;
		adj[p].push_back({i, c});
	}
	precalc(0);
	dfs(0);
	ll ans = 1e9;
	for(int i = 0; i < MAXN; ++i) ans = min(ans, dp[0][i]);
	bool found = 0;
	for(int i = n; i < n + m; ++i){
		if(dp[0][walk[i]] == ans) found = 1;
	}
	assert(found);
	cout << ans;
	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... |