이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
const int N = 5001;
const long long inf = (long long) 4e18L;
int n, m;
vector<pair<int, long long>> g[N];
long long dp[N][302];
long long sol(int u, int left) {
	if (g[u].size() == 0) {
		assert(left == 0);
		return 0;
	}
	long long& ret = dp[u][left];
	if (ret != -1) {
		return ret;
	}
	ret = 0;
	for (pair<int, long long> _p : g[u]) {
		long long sub = inf;
		int v = _p.first;
		long long w = _p.second;
		if (g[v].size() == 0) {
			sub = abs(w - left);
			ret += sub;
			continue;
		}
		for (int j = 0; j <= left; j++) {
			sub = min(sub, abs(w - j) + sol(v, left - j));
		}
		ret += sub;
	}
	return ret;
}
int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin >> n >> m;
	long long res = 0;
	for (int i = 1; i < n + m; i++) {
		int p;
		long long c;
		cin >> p >> c;
		g[p - 1].emplace_back(i, c);
		res += c;
	}
	memset(dp, -1, sizeof dp);
	for (int i = 14; i < 15; i++) {
		res = min(res, sol(0, i));
	}
	cout << res << '\n';
	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... |